<?php


namespace App\Http\Controllers\Api;


use App\Jobs\CalculateFollowsNumJob;
use App\Jobs\CalculateLikesNumJob;
use App\Jobs\Circle\ForgetCircleUnreadCountJob;
use App\Jobs\CreatePostSyncJob;

use App\Jobs\ImitateCircleJoinStepJob;
use App\Jobs\Posts\UpdatePosterGlassJob;
use App\Jobs\Posts\UpdatePostFieldsJob;
use App\Jobs\Posts\UpdatePostFilesIdJob;
use App\Jobs\Posts\UpdatePostGoodsIdJob;
use App\Jobs\Posts\UpdatePostOnlyTextJob;
use App\Jobs\Posts\UpdatePostSoundsIdJob;
use App\Jobs\Posts\UpdatePostTagIdJob;
use App\Jobs\Posts\UpdatePostVideoIdJob;
use App\Jobs\TopicImgJob;
use App\Jobs\UpdateCommentCircleJob;
use App\Jobs\UserInputSafeCheckJob;
use App\Jobs\UserPublishedFollowJob;
use App\Jobs\VideoSnapshotJob;
use App\Lib\WeApp\WeApp;
use App\Models\Bureau\WxBureau;
use App\Models\Posts\WxPost;
use App\Models\Posts\WxPostsAddress;
use App\Models\Posts\WxPostsField;
use App\Models\Posts\WxPostsFile;
use App\Models\Posts\WxPostsGoods;
use App\Models\Posts\WxPostsImg;
use App\Models\Posts\WxPostsSound;
use App\Models\Posts\WxPostsVote;
use App\Models\Posts\WxPostsWeightRefresh;
use App\Models\Posts\WxTag;
use App\Models\Circle\WxCircle;
use App\Models\Posts\WxPostsPayContent;
use App\Models\Posts\WxUserCircle;
use App\Models\Shop\WxShopGoods;
use App\Models\Used\WxUsedGood;
use App\Models\Used\WxUsedNeed;
use App\Models\User\WxUser;
use App\Models\User\WxUserPay;
use App\Models\User\WxUserStudentCertify;
use App\Models\Voter\WxVoter;
use App\Models\WxTenant;
use App\Wen\Utils\BaiduUtils;
use App\Wen\Utils\CircleUtils;
use App\Wen\Utils\FieldUtils;
use App\Wen\Utils\FileUtils;
use App\Wen\Utils\GatewayUtils;
use App\Wen\Utils\ImageUtils;
use App\Wen\Utils\PostUtils;
use App\Wen\Utils\SearchUtils;
use App\Wen\Utils\Settings;
use App\Wen\Utils\StrUtils;
use App\Wen\Utils\UserUtils;
use App\Wen\Utils\Utils;
use App\Http\Controllers\Api\Repositories\PostsRepositores;
use App\Http\Controllers\Api\Repositories\WxCircleRepositores;
use App\Http\Controllers\Api\Repositories\WxCommentRepositores;
use App\Http\Controllers\Api\Repositories\WxPlateRepositores;
use App\Http\Controllers\Api\Repositories\WxTagsRepositories;
use App\Http\Controllers\Api\Repositories\WxUserRepositores;
use App\Http\Requests\Api\PostsRequests\CircleRequest;
use App\Models\Posts\WxPost as Model;
use App\Models\Posts\WxPostsTag;
use App\Models\Posts\WxPostsVideo;
use App\Models\WxExceptional;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Intervention\Image\Facades\Image;
use SimpleSoftwareIO\QrCode\Facades\QrCode;


class PostsController extends BaseController
{
    /**
     * 板块选择
     */
    public function plateOptions()
    {
        $data = (new WxPlateRepositores())->options();
        return $this->success($data);
    }


    /**
     * 板块列表
     * @return \Illuminate\Http\JsonResponse
     */
    public function plateList()
    {
        return $this->success(WxPlateRepositores::list());
    }

    /**
     * 通过板块ID获取圈子列表
     * @param CircleRequest $request
     */
    public function getCircleByPlateId(CircleRequest $request)
    {
        $plateId = $request->plate_id;
        $uid = $request->uid;
        if($uid > 0){

        }else{
            $uid = 0;
        }
        $data = WxCircleRepositores::circleByPlateId($plateId, $uid);
        if($data){
            return $this->success($data);
        }else{
            return $this->fail(200003, [], '该分区没有'.env('circle_call', '圈子'));
        }

    }

    /**
     * 搜索圈子
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function searchCircle(Request $request)
    {
        $keyword = $request->keyword;
        return $this->success(WxCircleRepositores::searchCircle($keyword));
    }

    /**
     * 发帖时推荐的话题
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function recommendTags(Request $request)
    {
        $search = $request->search;
        if($search){
            $result = WxTag::where('tags_state', 0)->where('tags_name', 'like', $search.'%')->limit(20)->get()->map(function ($items) {
                $items->tags_number = WxPostsTag::where('tags_id', $items->id)->count();
                if(_empty_($items->head_portrait)){
                    $items->head_portrait = Settings::get('img_default_topic_avatar');
                    TopicImgJob::dispatch($items->id);
                }
                return $items;
            });
            return $this->success($result);
        }else{
            return $this->success(WxTagsRepositories::recommendTags());
        }

    }

    /**
     * 购买付费内容
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function pay(Request $request){
        $uid = $request->uid;
        $post_id = $request->post_id;
        $scene = $request->scene;

        if(_empty_($post_id) || _empty_($scene)){
            return $this->fail(200001);
        }

        $post_obj = WxPost::where('id', $post_id)->first(['user_id','pay_content_id', 'circle_id']);
        if(_empty_($post_obj)){
            return $this->fail(200003);
        }

        $post_user_id = $post_obj->user_id;
        $pay_content_id = $post_obj->pay_content_id;
        $circle_id = $post_obj->circle_id;

        if(_empty_($pay_content_id)){
            return $this->fail(200004);
        }

        if($uid == $post_user_id){
            return $this->fail(200038);
        }

        if(WxUserPay::where([
            ['user_id', '=', $uid],
            ['post_id', '=', $post_id],
            ['pay_content_id', '=', $pay_content_id]
        ])->exists()){
            return $this->fail(200035);
        }


        $pay_content_obj = WxPostsPayContent::find($pay_content_id);
        if(_empty_($pay_content_obj)){
            return $this->fail(200003);
        }

        try{
            DB::beginTransaction();
            $price = $pay_content_obj->price;
            $credit_type = $pay_content_obj->credit_type;

            $user = WxUser::find($uid);
            $user_name = $user->user_name;
            $is_vip = $user->is_member;
            $vip_discount = _between_(Settings::get('app_vip_paycontent_discount', 0), 0, 100);
            $vip_price_tip = '';
            if($vip_discount > 0 && $is_vip){
                if($credit_type == 0){
                    $vip_price = (int)($price * ( (100 - $vip_discount) / 100));
                }else{
                    $vip_price = round($price * ( (100 - $vip_discount) / 100), 2);
                }
                $vip_price_tip = '会员价';
            }else{
                $vip_price = $price;
            }

            if($credit_type == 0){
                $coins = UserUtils::user_coins($uid);

                if($coins < $vip_price){
                    DB::rollBack();
                    return $this->fail(200011);
                }


                $circle_user_reward = 0;
                $paycontent_division = 0;
                if($circle_id && $circle_id > 0){
                    $circle_info = WxCircle::find($circle_id);
                    $paycontent_division = $circle_info->circle_user_paycontent_division;
                    $circle_user_id = $circle_info->user_id;
                    $circle_user_reward = (int)($paycontent_division * $price);
                }


                $platform_division = _between_(Settings::get('app_paypost_platform_percent', 0), 0, 100);
                $platform_reward = (int)($platform_division * $price / 100);

                if($vip_price > 0){
                    $r = UserUtils::update_user_coins($uid,1, -$vip_price, $vip_price_tip.'购买付费内容：'.Settings::get('app_coin_name', '硬币').'-'.$vip_price);
                }else{
                    $r = true;
                }

                if($r){
                    if($circle_user_reward > 0 || $platform_reward > 0){
                        $author_reward =  $price - $circle_user_reward - $platform_reward;

                        if($author_reward > 0){
                            $content_tip = '「<a href="/pages/user/user?id='.$uid.'">'.$user_name.'</a>」购买了您的付费内容(id:<a href="/pages/sticky/sticky?id='.$post_id.'">'.$post_id.'</a>)，获得'.Settings::get('app_coin_name', '硬币').'+'.$author_reward.'('.env('circle_user_call', '圈主').'分成'.$circle_user_reward.Settings::get('app_coin_name', '硬币').'，系统分成'.$platform_reward.Settings::get('app_coin_name', '硬币').')';
                            UserUtils::update_user_coins($post_user_id,2, $author_reward, '付费内容被购买('.env('circle_user_call', '圈主').'分成'.($paycontent_division * 100).'%)：'.Settings::get('app_coin_name', '硬币').'+'.$author_reward);
                            UserUtils::add_user_notice(7003, $post_user_id,
                                Settings::get('app_coin_name', '硬币').'到账', $content_tip
                                , 100, $post_id);
                        }


                        if($circle_user_reward > 0){
                            UserUtils::update_user_coins($circle_user_id,15, $circle_user_reward, env('circle_user_call', '圈主').'分成奖励：'.Settings::get('app_coin_name', '硬币').'+'.$circle_user_reward);
                            UserUtils::add_user_notice(7004, $circle_user_id, env('circle_user_call', '圈主').'分成奖励', env('circle_call', '圈子').'成员的付费内容被购买，订单金额'.$price.'金币，您获得分成'.$circle_user_reward.'金币(分成比例：'.($paycontent_division * 100).'%)', 100);
                        }

                    }else{
                        UserUtils::update_user_coins($post_user_id,2, $price, '付费内容被购买：'.Settings::get('app_coin_name', '硬币').'+'.$price);
                        UserUtils::add_user_notice(7003, $post_user_id, Settings::get('app_coin_name', '硬币').'到账','「<a href="/pages/user/user?id='.$uid.'">'.$user_name.'</a>」购买了您的付费内容(id:<a href="/pages/sticky/sticky?id='.$post_id.'">'.$post_id.'</a>)，获得金币+'.$price, 100, $post_id);
                    }

                    $user_pay = new WxUserPay();
                    $user_pay->user_id = $uid;
                    $user_pay->post_id = $post_id;
                    $user_pay->pay_content_id = $pay_content_id;
                    $user_pay->save();
                    WxCommentRepositores::add($post_id, 0, 0, $uid,  '💰'.$vip_price_tip.'购买了付费内容', '', 1);

                    // 返回刷新内容
                    $data = WxPost::where('id', $post_id)->get();
                    $data = PostsRepositores::postsParame($data, $uid, $scene);
                    DB::commit();
                    return $this->success($data);
                }
                DB::rollBack();
                return $this->fail(200037);
            }else if($credit_type == 1){
                DB::rollBack();
                return $this->fail(200004, [], '该接口仅能购买'.Settings::get('app_coin_name', '硬币').'付费内容');
            }
        }catch (\Exception $e){
            DB::rollBack();
            _logger_(__file__, __line__, $e->getMessage());
            return $this->fail(200037);
        }
    }


    /**
     * 添加话题
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addTag(Request $request)
    {
        $tags_name = $request->tags_name;
        $uid = $request->uid;

        _limit_user('add:tag', $uid, 16);

        if(mb_strlen($tags_name) > 20){
            return $this->fail(200018);
        }

        // 百度审核
        $need_manual_review = true;
        $is_audit_create_tag = Settings::get('is_audit_create_tag', 0);
        if ($is_audit_create_tag == 2) {
            $filter_result = BaiduUtils::text_filter($tags_name);
            if($filter_result){
                if($filter_result['hit_level'] == 2){
                    // 不合规
                    return $this->fail(200016, ['tip'=>$filter_result['tip_list'], 'hit_word'=>$filter_result['hit_word']]);
                }else if($filter_result['hit_level'] == 0){
                    // 审核通过
                    $need_manual_review = false;
                }
            }
        }else if($is_audit_create_tag == 0){
            $need_manual_review = true;
        }else{
            $need_manual_review = false;
        }

        // (0正常，1管理员隐藏)
        $tags_state = 0;
        if($need_manual_review){
            $tags_state = 1;
        }

        UserInputSafeCheckJob::dispatch($uid, $tags_name);
        $res = WxTagsRepositories::add($uid, $tags_name, $tags_state);

        return $this->success($res);
    }


    private function updatePost(Request &$request){
        $uid = $request->uid;
        $posts_id = _abs($request->posts_id);
        global $__MINI_GLOBAL_IP__,$__MINI_GLOBAL_TENANT_ID__,$__MINI_GLOBAL_PAYCODE_5__;
        if(_empty_($posts_id)){
            return $this->fail(200001);
        }
        $the_post = WxPost::find($posts_id);
        if(_empty_($the_post)){
            return $this->fail(200003);
        }
        $is_admin = is_object_user_special($uid, $the_post->tenant_id);
        // 权限验证
        if(!$is_admin && !PostUtils::is_post_author($posts_id, $uid)){
            return $this->fail(200000);
        }
        if(!UserUtils::is_user_can_speak($uid)){
            return $this->fail(200043, [
                'title' => '禁言中，无法言论',
                'content' => '是否前往解除限制',
                'confirmText' => '去解除',
                'target_type' => 6,
                'target_id' => '/pagesA/mine/unlock/unlock?user_id='.$uid
            ], '您当前处于禁言期间，无法言论');
        }
        $the_post = WxPost::find($posts_id);
        $post_author_id = $the_post->user_id;
        if($the_post->refer_id > 0 || $the_post->vote_id > 0){
            if($the_post->refer_id > 0){
                return $this->fail(200000, [], '转发笔记不能编辑');
            }
            if($the_post->vote_id > 0){
                return $this->fail(200000, [], '投票笔记不能编辑');
            }
        }


        $edit_need_coin = Settings::get('app_publish_edit_need_coin', ($__MINI_GLOBAL_TENANT_ID__ > 0 ? Settings::get('app_publish_edit_need_coin', 100) : 100),  true);
        if($edit_need_coin > 0){
            // 判断金币是否足够
            if($post_author_id == $uid){
                if(UserUtils::user_coins($post_author_id) < $edit_need_coin){
                    return $this->fail(200011, []);
                }
            }
        }
        $contents = trim($request->posts_content);
        $circle_id = $request->circle_id;
        if(_empty_($circle_id)){
            $circle_id = null;
        }
        $refer_id = $request->refer_id;
        $voter_id = _empty_default_($request->voter_id, 0);

        $editer = $request->editer ?? 'simple';
        $posts_title = _empty_default_($request->posts_title, '');
        $imagetext_content = trim($request->imagetext_content) ?? '';
        $image_state_change_list = [];

        // [["id" => 74,"tags_name" => "啦啦啦啦"],]
        $tags = $request->tags;
        // [ ["id" => 1045,"name" => "爬宠饲养盒","pic" => "url"], ]
        $goods = $request->goods;
        // [
        //    "latitude" => 32.45217
        //    "longitude" => 118.43575
        //    "address_name" => "安徽省滁州市来安县东大街9号"
        //    "address_detailed" => "来安县新安镇永阳社区综治中心(白云商厦东北)"
        //    ]
        $address = $request->address;

        // [ ["url" => "url"], ]
        $image_urls = $request->image_urls;
        // null || video_url
        $video_urls = $request->video_url;
        // null || img_url
        $videoThumbUrl = Utils::isImgUrl($request->video_thumb_url) ? $request->video_thumb_url : '';
        // 0 || 1080
        $video_width = $request->video_width;
        // 0 || 1080
        $video_height = $request->video_height;

        $useds = _empty_default_($request->useds, []);

        $bureaus = _empty_default_($request->bureaus, []);

        $sph_obj = null;

        $votes = [];

        $file_list = $request->file_list;

        $sounds_list = $request->sounds_list;

        $contact_phone = $request->contact_phone;

        $pay_obj = $request->pay_obj;

        $is_anonymous = _empty_default_($request->is_anonymous, 0) == 1 ? 1 : 0;

        $check_res = $this->checkPost($editer, $is_only_text, $request, $image_state_change_list, $posts_title, $contents, $imagetext_content,$image_urls,$video_urls, $videoThumbUrl,
            $refer_id, $useds, $bureaus, $votes, $sph_obj, $file_list, $sounds_list, $contact_phone, $pay_obj, $voter_id);
        if ($check_res instanceof JsonResponse) {
            return $check_res;
        }

        if($pay_obj && _array_key($pay_obj, 'price', 0) > 0){
            if(WxPostsPayContent::where('post_id', $posts_id)->exists()){

            }else{
                return $this->fail(200004, [], '笔记不能从免费变更成付费付费');
            }
        }

        // 圈子权限检验
        $circle = null;
        if(_empty_($refer_id) && $circle_id){
            $circle = WxCircle::find($circle_id);
            if(Settings::get('app_publish_circle_required', 0, true) == 1){
                if($circle){

                }else{
                    return $this->fail(200004, [], '请选择一个'.env('circle_call', '圈子').'再发布吧');
                }
            }
        }

        if(!_empty_($refer_id)){
            $circle = null;
            $circle_id = null;
        }
        // 百度审核
        if(UserUtils::user_permissions_check_by_config($uid, 'audit_posts_white_list')){
            $need_manual_review = false;
        }else{
            $need_manual_review = true;
            $setting_is_audit_posts = Settings::get('is_audit_posts', 0);
            if ($setting_is_audit_posts == 2) {
                $filter_result = BaiduUtils::text_filter($contents);
                if($filter_result){
                    if($filter_result['hit_level'] == 2){
                        // 不合规
                        return $this->fail(200016, ['tip'=>$filter_result['tip_list'], 'hit_word'=>$filter_result['hit_word']]);
                    }else if($filter_result['hit_level'] == 0){
                        // 审核通过
                        $need_manual_review = false;
                    }
                }
            }else if($setting_is_audit_posts == 0){
                $need_manual_review = true;
            } else{
                $need_manual_review = false;
            }
        }
        // (0待审核，1审核通过，2驳回)
        $is_examine = 1;
        if($need_manual_review){
            $is_examine = 0;
        }


        // 更新
        $contents = trim($contents);
        $post_conetnt = _mini_phone( _mini_emoji( _mini_aite_replace( $contents ) ) );
        $updates = [
            'posts_content' => $post_conetnt,
        ];

        if(!_empty_($posts_title)){
            $updates['posts_title'] = $posts_title;
        }
        $updates['is_examine'] = $is_examine;

        if($circle_id > 0){
            $updates['circle_id'] = $circle_id;
            $updates['circle_name'] = ($circle && !_empty_(_array_key($circle, 'circle_name', null))) ? $circle['circle_name'] : '广场';
        }

        if($sph_obj){
            $updates['is_wechat_sph'] = true;
        }

        if(!_empty_($useds)){
            $updates['useds'] = implode(',', $useds);
        }

        if(!_empty_($bureaus)){
            $updates['bureaus'] = implode(',', $bureaus);
        }

        if($contact_phone){
            $updates['has_fields'] = 1;
        }

        if($voter_id > 0){
            $updates['voter_id'] = $voter_id;
        }else{
            $updates['voter_id'] = 0;
        }

        if (!_empty_($address) && _array_key($address, 'address_name', '')) {
            // 有地址
            $the_address = WxPostsAddress::updateOrCreate([
                'longitude'=>$address['longitude'], 'latitude'=>$address['latitude']
            ], [
                'address_name' => $address['address_name'],
                'address_detailed' => $address['address_detailed'],
            ]);
            if($the_address){
                $updates['address_id'] = $the_address->id;
            }
        }else{
            $updates['address_id'] = 0;
        }

        WxPostsGoods::where('posts_id', $posts_id)->forceDelete();
        if (!_empty_($goods)) {
            $updates['goods_id'] = '0';
        }else{
            $updates['goods_id'] = '';
        }

        if (!_empty_($file_list)) {
            $updates['files_id'] = '0';
        }else{
            $updates['files_id'] = '';
        }

        if (!_empty_($sounds_list)) {
            $updates['sounds_id'] = '0';
        }else{
            $updates['sounds_id'] = '';
        }

        WxPostsTag::where('posts_id', $posts_id)->forceDelete();
        if (!_empty_($tags)) {
            $updates['goods_id'] = '0';
        }else{
            $updates['goods_id'] = '';
        }

        if(!_empty_($votes)){
            $updates['vote_id'] = null;
        }else{
            $updates['vote_id'] = 0;
//            WxPostsVote::where('posts_id', $posts_id)->forceDelete();
        }

        if($is_anonymous){
            if($is_anonymous == 1 && Settings::get('app_vip_anonymous_only', 0) == 1){
                if(!$is_admin){
                    $post_author = WxUser::find($post_author_id);
                    if($post_author && $post_author->is_member){

                    }else{
                        return $this->fail(200043, [
                            'title' => '仅会员可用',
                            'content' => '匿名属于会员特权，是否前往开通',
                            'confirmText' => '前往开通',
                            'target_type' => 6,
                            'target_id' => '/pagesA/mine/members/members'
                        ], '仅会员可用');
                    }
                }
            }
            $updates['is_anonymous'] = 1;
        }else{
            $updates['is_anonymous'] = 0;
        }

        DB::beginTransaction();
        try {
            // todo:
            $updates['is_only_text'] = null;
            $r = WxPost::where('id', $posts_id)->update($updates);

            if($r){
                if($edit_need_coin > 0){
                    if($post_author_id == $uid){
                        UserUtils::update_user_coins($post_author_id, 28, -$edit_need_coin, '重新编辑笔记(id: '.$posts_id.')花费了'.$edit_need_coin.Settings::get('app_coin_name', '硬币').'。');
                    }
                }
                // 先检验是否顺序是一样的，或者是仅仅新添加了图片，未改变顺序
                if(true){
                    $current_urls = [];
                    $old_img_urls = WxPostsImg::where('posts_id', $posts_id)->pluck('img_url')->toArray();
                    $image_urls_ = $image_urls;
                    if (!_empty_($image_urls)) {
                        foreach ($image_urls as $k => $v) {
                            $current_urls[] = $v['url'];
                        }
                    }
                    if(_empty_($old_img_urls) || _empty_($current_urls)){
                        if(_empty_($current_urls)){
                            WxPostsImg::where('posts_id', $posts_id)->forceDelete();
                        }
                    }else{
                        $is_all_equal = false;
                        $is_pre_equal = false;
                        if(count($current_urls) == count($old_img_urls)){
                            $is_all_equal = true;
                            for ($i = 0; $i<count($current_urls); $i ++){
                                if($current_urls[$i] != $old_img_urls[$i]){
                                    $is_all_equal = false;
                                }
                            }
                        }else if(count($current_urls) > count($old_img_urls)){
                            $is_pre_equal = true;
                            for ($i = 0; $i<count($old_img_urls); $i ++){
                                if($current_urls[$i] != $old_img_urls[$i]){
                                    $is_pre_equal = false;
                                }
                            }
                            if($is_pre_equal){
                                $image_urls_ = array_slice($image_urls_, count($old_img_urls));
                            }
                        }

                        if($is_all_equal || $is_pre_equal){
                            if($is_all_equal){
                                $image_urls_ = [];
                            }
                        }else{
                            WxPostsImg::where('posts_id', $posts_id)->forceDelete();
                        }
                    }

                    if (!_empty_($image_urls_)) {
                        $postImage = [];
                        foreach ($image_urls_ as $k => $v) {
                            $postImage[$k]['posts_id'] = $posts_id;
                            $postImage[$k]['user_id'] = $post_author_id;
                            $postImage[$k]['img_url'] = $v['url'];

                            if(!StrUtils::endsWith($v['url'] ?? '', '.gif')){
                                $img_info = ImageUtils::get_url_img_info($v['url']);
                                if($img_info){
                                    $postImage[$k]['width'] = $img_info['width'];
                                    $postImage[$k]['height'] = $img_info['height'];
                                }
                            }else{
                                $postImage[$k]['width'] = 0;
                                $postImage[$k]['height'] = 0;
                            }
                        }
                        $postImg = new WxPostsImg();
                        $postImg->addAll($postImage);
                    }
                }


                if(true){
                    $current_urls = [];
                    $old_file_urls = WxPostsFile::where('post_id', $posts_id)->pluck('url')->toArray();
                    $files_ = $file_list;
                    if (!_empty_($file_list)) {
                        foreach ($file_list as $k => $v) {
                            $current_urls[] = $v['url'];
                        }
                    }
                    if(_empty_($old_file_urls) || _empty_($current_urls)){
                        if(_empty_($current_urls)){
                            WxPostsFile::where('post_id', $posts_id)->forceDelete();
                        }
                    }else{
                        $is_all_equal = false;
                        $is_pre_equal = false;
                        if(count($current_urls) == count($old_file_urls)){
                            $is_all_equal = true;
                            for ($i = 0; $i<count($current_urls); $i ++){
                                if($current_urls[$i] != $old_file_urls[$i]){
                                    $is_all_equal = false;
                                }
                            }
                        }else if(count($current_urls) > count($old_file_urls)){
                            $is_pre_equal = true;
                            for ($i = 0; $i<count($old_file_urls); $i ++){
                                if($current_urls[$i] != $old_file_urls[$i]){
                                    $is_pre_equal = false;
                                }
                            }
                            if($is_pre_equal){
                                $files_ = array_slice($files_, count($old_file_urls));
                            }
                        }

                        if($is_all_equal || $is_pre_equal){
                            if($is_all_equal){
                                $files_ = [];
                            }
                        }else{
                            WxPostsFile::where('post_id', $posts_id)->forceDelete();
                        }
                    }

                    if(!_empty_($files_)){
                        foreach ($files_ as $file){
                            if($file['name'] && $file['url']){
                                $file_model = new WxPostsFile();
                                $file_model->name = $file['name'];
                                $file_model->url = $file['url'];
                                $file_model->size = _array_key($file, 'size', 0);
                                $file_model->post_id = $posts_id;
                                $file_model->save();
                            }
                        }
                    }
                }

                if(true){
                    $current_urls = [];
                    $old_sound_urls = WxPostsSound::where('post_id', $posts_id)->pluck('url')->toArray();
                    $sounds_list_ = $sounds_list;
                    if (!_empty_($sounds_list)) {
                        foreach ($sounds_list as $k => $v) {
                            $current_urls[] = $v['url'];
                        }
                    }
                    if(_empty_($old_sound_urls) || _empty_($current_urls)){
                        if(_empty_($current_urls)){
                            WxPostsSound::where('post_id', $posts_id)->forceDelete();
                        }
                    }else{
                        $is_all_equal = false;
                        $is_pre_equal = false;
                        if(count($current_urls) == count($old_sound_urls)){
                            $is_all_equal = true;
                            for ($i = 0; $i<count($current_urls); $i ++){
                                if($current_urls[$i] != $old_sound_urls[$i]){
                                    $is_all_equal = false;
                                }
                            }
                        }else if(count($current_urls) > count($old_sound_urls)){
                            $is_pre_equal = true;
                            for ($i = 0; $i<count($old_sound_urls); $i ++){
                                if($current_urls[$i] != $old_sound_urls[$i]){
                                    $is_pre_equal = false;
                                }
                            }
                            if($is_pre_equal){
                                $sounds_list_ = array_slice($sounds_list_, count($old_sound_urls));
                            }
                        }

                        if($is_all_equal || $is_pre_equal){
                            if($is_all_equal){
                                $sounds_list_ = [];
                            }
                        }else{
                            WxPostsSound::where('post_id', $posts_id)->forceDelete();
                        }
                    }

                    if(!_empty_($sounds_list_)){
                        foreach ($sounds_list_ as $sound){
                            $sound_model = new WxPostsSound();
                            $sound_model->name = $sound['name'];
                            $sound_model->time = $sound['time'];
                            $sound_model->url = $sound['url'];
                            $sound_model->post_id = $posts_id;
                            $sound_model->save();
                        }
                    }
                }

                if (!_empty_($video_urls)) {

                    $video_updates = [
                        'video_url' => $video_urls,
                        'video_thumb_url' => $videoThumbUrl,
                        'video_width' => $video_width,
                        'video_height' => $video_height
                    ];
                    $attachment = FileUtils::get_url_attach($video_urls);
                    if($attachment->state == 2){
                        // 状态(0正常，1用户删除，2管理员下架, 3审核中 4冻结中 5已清理)
                        $video_updates['posts_video_state'] = 5;
                    }else if($attachment->state == 3 || $attachment->state == 4){
                        $video_updates['posts_video_state'] = 4;
                    }else if(in_array($attachment->cos_review, [3,4,5])){
                        $video_updates['posts_video_state'] = 3;
                    }
                    WxPostsVideo::updateOrCreate(['posts_id'=>$posts_id, 'user_id'=>$post_author_id], $video_updates);
                }

                if(!_empty_($votes)){
                    $vote_updates = [];
                    foreach ([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20] as $num){
                        if(_array_key($votes, $num - 1, '')){
                            $vote_updates['option'.$num] = _array_key($votes, $num - 1, '');
                        }
                    }
                    WxPostsVote::updateOrCreate([
                        'post_id' => $posts_id
                    ],$vote_updates);
                }

                Utils::image_state_change($image_state_change_list, 1);
                if($pay_obj && _array_key($pay_obj, 'price', 0) > 0){
                    WxPostsPayContent::where('post_id', $posts_id)->update([
                        'words_percent' => _array_key($pay_obj, 'words_percent', 100),
                        'is_file' => _array_key($pay_obj, 'is_file', 0),
                        'is_img' => _array_key($pay_obj, 'is_img', 0),
                        'is_video' => _array_key($pay_obj, 'is_video', 0),
                        'is_sound' => 0,
                        'hidden' => _array_key($pay_obj, 'hidden', ''),
                        'price' => _array_key($pay_obj, 'price', 0),
                        'credit_type' => _array_key($pay_obj, 'credit_type', 0)
                    ]);
                }

                if (!_empty_($goods)) {
                    $postGoods = [];
                    foreach ($goods as $k => $v) {
                        $postGoods[$k]['posts_id'] = $posts_id;
                        $postGoods[$k]['goods_id'] = $v['id'];
                        Redis::sadd('realtime:others:set', json_encode([$v['id'], 3, 10]));
                    }
                    $goods = new WxPostsGoods();
                    $goods->addAll($postGoods);
                }

                if (!_empty_($tags)) {
                    $postTag = [];
                    $tagsIds = [];
                    foreach ($tags as $k => $v) {
                        $postTag[$k]['posts_id'] = $posts_id;
                        $postTag[$k]['tags_id'] = $v['id'];
                        $tagsIds[] = $v['id'];
                        Redis::sadd('realtime:others:set', json_encode([$v['id'], 5, 10]));
                    }
                    $tags = new WxPostsTag();
                    $tags->addAll($postTag);
                    WxTag::whereIn('id', $tagsIds)->increment('tags_number');
                    if($circle_id > 0){
                        CircleUtils::add_circle_tags($circle_id, $tagsIds);
                    }
                }


                if(_array_key($updates, 'has_fields', 0) == 1){
                    WxPostsField::updateOrCreate(['post_id'=>$posts_id],['contact_phone'=>$contact_phone]);
                }else{
                    if(_empty_($contact_phone)){
                        WxPostsField::updateOrCreate(['post_id'=>$posts_id],['contact_phone'=>null]);
                    }
                }
                if($circle_id > 0){
                    Redis::sadd('realtime:others:set', json_encode([$circle_id, 2, 10]));
                }
                Redis::sadd('realtime:others:set', json_encode([$post_author_id, 4, 10]));
                if(_array_key($updates, 'is_wechat_sph', false) == true){
                    update_post_meta($posts_id, 'wechat_sph', $sph_obj, 'j');
                }

                if($circle_id){
                    Cache::forget('circle:postCount:'.$circle_id);
                }
                Cache::forget('user:post:count:'.$post_author_id);
                // 视频封面
                if($video_urls && _empty_($videoThumbUrl)){
                    VideoSnapshotJob::dispatch(WxPostsVideo::where('posts_id', $posts_id)->value('id'));
                }

                Cache::forget('posts:post_type:'.$posts_id);
                Cache::forget('get_the_title:'.$posts_id.':30');
                Cache::forget('get_the_title:'.$posts_id.':15');
                Cache::forget('get_the_title:'.$posts_id.':100');
                Cache::forget('get:post:goods:'.$posts_id);
                Cache::forget('get:post:tags:'.$posts_id);
                Cache::forget('get:post:files:'.$posts_id);
                Cache::forget('get:post:sounds:'.$posts_id);

                UpdatePostVideoIdJob::dispatch($posts_id);
                UpdatePostTagIdJob::dispatch($posts_id);
                UpdatePostOnlyTextJob::dispatch($posts_id);

                if($is_examine === 0){
                    UserUtils::assistant_notice_review(101, $posts_id);
                }

                DB::commit();;
                return $this->success(['id'=>$posts_id, 'post_id'=>$posts_id, 'tip'=> '修改成功',  'ok' => Settings::get('app_publish_success_popup', 0) == 1 ? 1 : 2, 'target_type' => -6, 'target_id' => '/pages/sticky/sticky?id='.$posts_id, 'promotion' => $__MINI_GLOBAL_PAYCODE_5__ ? 1 : 0]);
            }
            DB::rollBack();
            return $this->fail(200006);
        } catch (\Exception $e) {
            DB::rollBack();
            _logger_(__file__, __line__, $e->getMessage());
            return $this->fail(200006);
        }

    }

    private function checkPost(&$editer, &$is_only_text, &$request, &$image_state_change_list, &$posts_title, &$contents, &$imagetext_content, &$image_urls, &$video_urls, &$videoThumbUrl,
                               &$refer_id, &$useds, &$bureaus, &$votes, &$sph_obj, &$file_list, &$sounds_list, &$contact_phone, &$pay_obj, $voter_id){
        global $__MINI_GLOBAL_PAYCODE_0__;
        // todo: 1
        if(true){
            if(_empty_($refer_id)){
                $refer_id = 0;
            }else{
                $refer_id = _abs($refer_id);
            }
            if($refer_id > 0){
                $refer_post_refer_id = WxPost::where('id', $refer_id)->value('refer_id');
                if($refer_post_refer_id > 0){
                    return $this->fail(200010, [], '该笔记为转发内容，不能再次转发');
                }
            }
            if(_empty_($voter_id)){
                $voter_id = 0;
            }else{
                $voter_id = _abs($voter_id);
            }
            if($voter_id > 0){
                if(WxVoter::where('id', $voter_id)->exists()){

                }else{
                    return $this->fail(200003, [], '鞋带的选票实际不存在');
                }
            }
        }


        // todo: 2
        if(true){
            if(!_empty_($useds)){
                $useds = explode(',', $useds);
                if(count(array_unique($useds)) != count($useds)){
                    return $this->fail(200004, [], '闲置商品有重复');
                }
                if(WxUsedGood::whereIn('id', $useds)->count() != count($useds)){
                    return $this->fail(200004, [], '闲置商品参数检验不合法');
                }
            }
            if(_empty_($useds)){
                $useds = [];
            }else{
                if(!is_array($useds)){
                    return $this->fail(200004, [], '闲置商品参数检验不合法');
                }
                if(count($useds) > 5){
                    return $this->fail(200004, [], '最多选择5个闲置商品');
                }
                $is_only_text = false;
            }
        }


        // todo: 3
        if(true){
            if(!_empty_($bureaus)){
                $bureaus = explode(',', $bureaus);
                if(count(array_unique($bureaus)) != count($bureaus)){
                    return $this->fail(200004, [], '组局有重复');
                }
                if(WxBureau::whereIn('id', $bureaus)->count() != count($bureaus)){
                    return $this->fail(200004, [], '组局参数检验不合法');
                }
            }
            if(_empty_($bureaus)){
                $bureaus = [];
            }else{
                if(!is_array($bureaus)){
                    return $this->fail(200004, [], '组局参数检验不合法');
                }
                if(count($bureaus) > 5){
                    return $this->fail(200004, [], '最多选择5个组局');
                }
                $is_only_text = false;
            }
        }

        // todo: 4
        if(true){
            $vote_list = $request->vote_list;
            if($vote_list && count($vote_list) >= 2){
                if(!$__MINI_GLOBAL_PAYCODE_0__){
                    return $this->fail(700000);
                }
                foreach ($vote_list as $vote){
                    if($vote['value']){
                        $votes[] = $vote['value'];
                    }
                }
                if(count($votes) != count($vote_list)){
                    return $this->fail(200004);
                }
            }
        }

        // todo: 5
        if(true){
            $sph_video_feed_token = $request->sph_video_feed_token;
            $sph_image_urls = $request->sph_image_urls;
            if(_empty_($sph_video_feed_token) || strpos($sph_video_feed_token, 'token/') !== 0){
                $sph_video_feed_token = null;
                $sph_image_urls = null;
            }else{
                $sph_video_feed_token = trim($sph_video_feed_token);
            }

            if(_empty_($sph_image_urls)){
                $sph_image_urls = null;
            }


            $sph_img = '';
            if($sph_video_feed_token){
                if($sph_image_urls && _array_key($sph_image_urls[0], 'url', '')){
                    $sph_img = $sph_image_urls[0]['url'];
                }
                $sph_obj = [
                    'type' => 'video',
                    'feed_token' => $sph_video_feed_token,
                    'img' => $sph_img
                ];
                if($sph_img){
                    $image_state_change_list[] = $sph_img;
                }
                $is_only_text = false;
            }
        }

        // todo: 6
        if(true){
            if(!_empty_($file_list)){
                if(count($file_list) > Settings::get('app_upload_max_files', 5, true)){
                    return $this->fail(200020);
                }
                foreach ($file_list as $file){
                    if(_empty_(_array_key($file, 'name', '')) || _empty_(_array_key($file, 'url', ''))){
                        return $this->fail(200019);
                    }
                }
            }else{
                $file_list = [];
            }
        }

        // todo: 7
        if(true){
            if(!_empty_($sounds_list)){
                if(!$__MINI_GLOBAL_PAYCODE_0__){
                    return $this->fail(700000);
                }
                if(count($sounds_list) > Settings::get('app_upload_max_sounds', 1, true)){
                    return $this->fail(200023);
                }
                foreach ($sounds_list as $sound){
                    if(_empty_(_array_key($sound, 'name', '')) || _empty_(_array_key($sound, 'url', '')) || _empty_(_array_key($sound, 'time', ''))){
                        return $this->fail(200024);
                    }
                    if(strpos($sound['url'], 'http') === false){
                        return $this->fail(200024);
                    }
                }
            }else{
                $sounds_list = [];
            }
        }

        // todo: 8
        if(true){
            if(!_empty_($contact_phone)){
                if(!StrUtils::is_phone_number($contact_phone)){
                    return $this->fail(200004, [], '联系手机号不合法');
                }
            }else{
                $contact_phone = null;
            }
        }

        // todo: 9
        if(true){
            if($pay_obj && _array_key($pay_obj, 'price', 0) > 0){
                if(_array_key($pay_obj, 'words_percent', 100) == 100 && _array_key($pay_obj, 'is_file', 0) == 0 && _array_key($pay_obj, 'is_img', 0) == 0 && _array_key($pay_obj, 'is_video', 0) == 0 && _array_key($pay_obj, 'hidden', '') == '' ){
                    return $this->fail(200029);
                }

                if(!in_array(_array_key($pay_obj, 'credit_type', 0), [0, 1])){
                    return $this->fail(200004);
                }

                global $__MINI_GLOBAL_PAYCODE_7__;
                if(!$__MINI_GLOBAL_PAYCODE_7__){
                    if(_array_key($pay_obj, 'is_file', 0) == 1){
                        return $this->fail(700000);
                    }
                    if(_array_key($pay_obj, 'credit_type', 0) == 1){
                        return $this->fail(700000);
                    }
                }

                if(_array_key($pay_obj, 'credit_type', 0) == 0){
                    if(_array_key($pay_obj, 'price', 0) > Settings::get('app_pay_max_coins', 10000)){
                        return $this->fail(200030);
                    }
                }else if(_array_key($pay_obj, 'credit_type', 0) == 1){
                    if(_array_key($pay_obj, 'price', 0) > Settings::get('app_pay_max_balance', 1000)){
                        return $this->fail(200030);
                    }
                }

                if(_array_key($pay_obj, 'words_percent', 100) < 100){
                    if(_array_key($pay_obj, 'words_percent', 100) > 90 || _array_key($pay_obj, 'words_percent', 100) < 50){
                        return $this->fail(200032);
                    }
                    if(mb_strlen(strip_tags($contents)) < 50){
                        return $this->fail(200031, [], '若开启篇幅付费，笔记内容不能少于50字');
                    }
                }

                if(_array_key($pay_obj, 'is_file', 100) == 1 && count($file_list) <= 0){
                    return $this->fail(200004);
                }

                if(_array_key($pay_obj, 'is_img', 100) == 1 && count($image_urls) <= 0){
                    return $this->fail(200004);
                }
                if(_array_key($pay_obj, 'is_video', 100) == 1 && _empty_($video_urls)){
                    return $this->fail(200004);
                }
                $is_only_text = false;
            }else{
                $pay_obj = [];
            }
        }

        if(true){
            // 内容修正部分
            if($editer == 'imagetext'){
                $contents = $imagetext_content;
                if(!preg_match('/<(img|video|table|audio|a)[^>]+>/is', $contents)){
                    $contents = strip_tags($contents, ['<a>', '<br>', '<p>']);
                }else{
                    $is_only_text = false;
                }
                $image_urls = null;
                $video_urls = null;
                $videoThumbUrl = null;
                $votes = null;
                $posts_title = trim(strip_tags($posts_title));
                if(_empty_($posts_title)){
                    $posts_title = '';
                }
            }else{
                $posts_title = '';
            }
            if($refer_id > 0){
                $contents = strip_tags($contents);
                $is_only_text = false;
            }
            $contents = PostUtils::post_icon_inline_process($contents);

            // 内容检测

            if(mb_strlen(strip_tags($contents)) <= 0){
                if($editer == 'imagetext'){
                    if(_empty_($posts_title)){
                        return $this->fail(200025);
                    }
                }else{
                    return $this->fail(200025);
                }
            }else if(preg_match('$这是一段示例$', strip_tags($contents))){
                return $this->fail(200026);
            }


            if($image_urls){
                foreach ($image_urls as $img){
                    if(is_array($img)){
                        $image_state_change_list[] = $img['url'];
                    }else{
                        $image_state_change_list[] = $img;
                    }
                }
                $is_only_text = false;
            }
            if($video_urls){
                $image_state_change_list[] = $video_urls;
                $is_only_text = false;
            }
            if($videoThumbUrl){
                $image_state_change_list[] = $videoThumbUrl;
            }
            if(!_empty_($file_list)){
                foreach ($file_list as $file){
                    $image_state_change_list[] = $file['url'];
                }
                $is_only_text = false;
            }

            if(!_empty_($sounds_list)){
                foreach ($sounds_list as $sound){
                    $image_state_change_list[] = $sound['url'];
                }
                $is_only_text = false;
            }

            preg_match_all("/<(img|video).*?src[^\'\"]+[\'\"]([^\"\']+)[^>]+>/is", $contents, $result);
            $post_images_arr = $result[2];
            if($post_images_arr){
                foreach ($post_images_arr as $url){
                    $image_state_change_list[] = $url;
                }
            }
        }
    }

    /**
     * 发帖
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addPost(Request $request)
    {
        global $__MINI_GLOBAL_PAYCODE_0__,$__MINI_GLOBAL_TENANT_ID__,$__MINI_GLOBAL_CURRENT_PLAYER_ID__,$__MINI_GLOBAL_DEVICE__,$__MINI_GLOBAL_IS_ADMIN_SUPER__,$__MINI_GLOBAL_PAYCODE_5__;
        $uid = $request->uid;

        $is_only_text = true;
        $is_admin = UserUtils::is_mini_admin($uid);

        if(true){
            if(!UserUtils::is_user_can_speak($uid)){
                return $this->fail(200043, [
                    'title' => '禁言中，无法言论',
                    'content' => '是否前往解除限制',
                    'confirmText' => '去解除',
                    'target_type' => 6,
                    'target_id' => '/pagesA/mine/unlock/unlock?user_id='.$uid
                ], '您当前处于禁言期间，无法言论');
            }

            if(!$is_admin && Cache::has('addPost:time:'.$__MINI_GLOBAL_TENANT_ID__.':'.$uid)){
                return $this->fail(200027);
            }

            if(!$is_admin  && !str_contains(env(_multi_key('APP_PUBLISH_POST_SPH_USER'), ''), $uid) && (WxPost::where('user_id', $uid)->where('tenant_id', $__MINI_GLOBAL_TENANT_ID__)->whereDate('created_at', current_time('day'))->count() >= Settings::get('app_publish_times_max', 3, true))){
                return $this->fail(200028);
            }

            $arr = UserUtils::user_action_permissions_check($uid, 'publish_post');
            if($arr['code'] == 0){
                return $this->fail(200000, [], $arr['msg']);
            }
            $user = WxUser::find($uid);
//            if(mb_strlen( str_replace( [Settings::get('default_user_name', '微信用户'), '微信用户', '普通用户'], '', $user->user_name )) != mb_strlen($user->user_name)){
//                return $this->fail(200041);
//            }
            // 验证资料
            if(Settings::get('app_publish_force_bind_phone', 0, true) == 1){
                if(_empty_($user->phone) && _empty_($__MINI_GLOBAL_CURRENT_PLAYER_ID__)){
                    return $this->fail(200043, [
                        'title' => '未绑定手机号',
                        'content' => '前往绑定',
                        'confirmText' => '去绑定',
                        'target_type' => 6,
                        'target_id' => '/pagesA/mine/editmine/editmine?phone=1'
                    ], '未绑定手机号');
                }
            }

            if(Settings::get('app_publish_force_real_name', 0, true) == 1){
                if(_empty_($user->real_name) && _empty_($__MINI_GLOBAL_CURRENT_PLAYER_ID__)){
                    return $this->fail(200043, [
                        'title' => '未实名认证',
                        'content' => '您还没有实名认证，是否前往认证',
                        'confirmText' => '去认证',
                        'target_type' => 6,
                        'target_id' => '/pagesA/mine/realname/realname'
                    ], '未实名认证');
                }
            }

            $force_university = Settings::get('app_publish_force_university', [], true);
            if(!_empty_($force_university)){
                if(_empty_($user->university)){
                    return $this->fail(200043, [
                        'title' => '未学生认证',
                        'content' => '您还没有学生认证，是否前往认证',
                        'confirmText' => '去认证',
                        'target_type' => 6,
                        'target_id' => '/pagesA/attestation/attestation'
                    ], '未学生认证');
                }else{
                    if(!in_array('-1', $force_university)) {
                        $student_certify = WxUserStudentCertify::find($user->id);
                        if ($student_certify) {
                            if (!in_array($student_certify->sid, $force_university)) {
                                return $this->fail(200000, [], '仅“' . Settings::get('app_publish_force_university_tip', '', true) . '”可发布');
                            }
                        }
                    }
                }
            }

            if(Settings::get('app_publish_force_subscribe_mp', 0, true) == 1){
                if(_empty_($user->weixin_mp_openid) && _empty_($__MINI_GLOBAL_CURRENT_PLAYER_ID__)){
                    $weapp = new WeApp('mp');
                    $mpServicer = $weapp->getMpServicer();
                    try {
                        $url = $mpServicer->getQrCodeWithPara(0, 'user:bind:'.$user->id);
                    }catch (\Exception $e){
                        return $this->fail(200006, [], '生成公众号二维码失败，请检查[全局配置-支付-微信-公众号]');
                    }
                    if($url){
                        $qrCode = QrCode::format('png')->size(300)->generate($url);
                        $image = Image::make($qrCode);
                        $image->resizeCanvas(300, 300 + 60, 'bottom', false, '#ffffff'); // 增加高度，保持宽高比，背景色为白色
                        $mp_app_name = Settings::get('mp_app_name', '');
                        $text_tip = '关注'.$mp_app_name.'公众号，可以更方便通知到您';
                        if(mb_strlen($mp_app_name) > 4){
                            $text_tip = '关注'.$mp_app_name.'公众号';
                        }
                        $image->text($text_tip, 150, 40, function($font){
                            $font->file(public_path('storage/font/DingTalk_JinBuTi_Regular.ttf')); // 字体文件路径
                            $font->size(13); // 字体大小
                            $font->color('#000000'); // 字体颜色
                            $font->align('center'); // 水平对齐
                            $font->valign('top'); // 垂直对齐
                        });
                        $base64 = 'data:image/png;base64,' . base64_encode($image->encode('png')->getEncoded());
                        return $this->fail(200043, [
                            'title' => '未关注公众号，无法实时获取通知',
                            'content' => '前往关注',
                            'confirmText' => '去关注',
                            'target_type' => 26,
                            'target_id' => $base64
                        ], '未关注公众号');
                    }
                }
            }
        }


        $contents = trim($request->posts_content);
        $circle_id = $request->circle_id;
        if(_empty_($circle_id)){
            $circle_id = null;
        }
        $refer_id = _empty_default_($request->refer_id, 0);
        $voter_id = _empty_default_($request->voter_id, 0);

        $editer = $request->editer ?? 'simple';
        $posts_title = _empty_default_($request->posts_title, '');
        $imagetext_content = trim($request->imagetext_content) ?? '';
        $image_state_change_list = [];

        // [["id" => 74,"tags_name" => "啦啦啦啦"],]
        $tags = $request->tags;
        // [ ["id" => 1045,"name" => "爬宠饲养盒","pic" => "url"], ]
        $goods = $request->goods;
        // [
        //    "latitude" => 32.45217
        //    "longitude" => 118.43575
        //    "address_name" => "安徽省滁州市来安县东大街9号"
        //    "address_detailed" => "来安县新安镇永阳社区综治中心(白云商厦东北)"
        //    ]
        $address = $request->address;

        // [ ["url" => "url"], ]
        $image_urls = $request->image_urls;
        // null || video_url
        $video_urls = $request->video_url;
        // null || img_url
        $videoThumbUrl = Utils::isImgUrl($request->video_thumb_url) ? $request->video_thumb_url : '';
        // 0 || 1080
        $video_width = $request->video_width;
        // 0 || 1080
        $video_height = $request->video_height;

        $useds = _empty_default_($request->useds, []);

        $bureaus = _empty_default_($request->bureaus, []);

        $sph_obj = null;

        $votes = [];

        $file_list = $request->file_list;

        $sounds_list = $request->sounds_list;

        $contact_phone = $request->contact_phone;

        $pay_obj = $request->pay_obj;

        $is_anonymous = _empty_default_($request->is_anonymous, 0) == 1 ? 1 : 0;
        if($is_anonymous == 1 && Settings::get('app_vip_anonymous_only', 0) == 1){
            if($user->is_member){

            }else{
                return $this->fail(200043, [
                    'title' => '仅会员可用',
                    'content' => '匿名属于会员特权，是否前往开通',
                    'confirmText' => '前往开通',
                    'target_type' => 6,
                    'target_id' => '/pagesA/mine/members/members'
                ], '仅会员可用');
            }
        }

        $check_res = $this->checkPost($editer, $is_only_text, $request, $image_state_change_list, $posts_title, $contents, $imagetext_content,$image_urls,$video_urls, $videoThumbUrl,
            $refer_id, $useds, $bureaus, $votes, $sph_obj, $file_list, $sounds_list, $contact_phone, $pay_obj, $voter_id);
        if ($check_res instanceof JsonResponse) {
            return $check_res;
        }

        // 圈子权限检验
        $circle = null;
        if(_empty_($refer_id) && $circle_id){
            $circle = WxCircle::find($circle_id);
            if(Settings::get('app_publish_circle_required', 0, true) == 1){
                if($circle){

                }else{
                    return $this->fail(200004, [], '请选择一个'.env('circle_call', '圈子').'再发布吧');
                }
            }
        }

        if(!_empty_($refer_id)){
            $circle = null;
            $circle_id = null;
        }
        // 百度审核
        if(UserUtils::user_permissions_check_by_config($uid, 'audit_posts_white_list')){
            $need_manual_review = false;
        }else if($sph_obj && !_empty_(_array_key($sph_obj, 'feed_token', '')) && str_contains(env(_multi_key('APP_PUBLISH_POST_SPH_USER'), ''), $uid)){
            $need_manual_review = false;
        }else{
            $need_manual_review = true;
            $setting_is_audit_posts = Settings::get('is_audit_posts', 0);
            if ($setting_is_audit_posts == 2) {
                $filter_result = BaiduUtils::text_filter($contents);
                if($filter_result){
                    if($filter_result['hit_level'] == 2){
                        // 不合规
                        return $this->fail(200016, ['tip'=>$filter_result['tip_list'], 'hit_word'=>$filter_result['hit_word']]);
                    }else if($filter_result['hit_level'] == 0){
                        // 审核通过
                        $need_manual_review = false;
                    }
                }
            }else if($setting_is_audit_posts == 0){
                $need_manual_review = true;
            } else{
                $need_manual_review = false;
            }
        }
        // (0待审核，1审核通过，2驳回)
        $is_examine = 1;
        if($need_manual_review){
            $is_examine = 0;
        }

        $pay_content_id = 0;
        if($pay_obj && _array_key($pay_obj, 'price', 0) > 0){
            $pay_content = new WxPostsPayContent();
            $pay_content->post_id = -$uid;
            $pay_content->words_percent = _array_key($pay_obj, 'words_percent', 100);
            $pay_content->is_file = _array_key($pay_obj, 'is_file', 0);
            $pay_content->is_img = _array_key($pay_obj, 'is_img', 0);
            $pay_content->is_video = _array_key($pay_obj, 'is_video', 0);
            $pay_content->is_sound = 0;
            $pay_content->hidden = _array_key($pay_obj, 'hidden', '');
            $pay_content->price = _array_key($pay_obj, 'price', 0);
            $pay_content->credit_type = _array_key($pay_obj, 'credit_type', 0);
            $pay_content->save();
            $pay_content_id = $pay_content->id;
            $is_only_text = false;
        }

        if(_empty_($refer_id) && $circle){
            $res = CircleUtils::user_can_publish($user, $circle);
            if($res['code'] == 0){
                return $this->fail(200000, [], $res['tip']);
            }else if($res['code'] == 200011 || $res['code'] == 200012){
                return $this->fail($res['code'], [], $res['tip']);
            }
        }

        if($image_state_change_list && count($image_state_change_list) > 0){
            $is_only_text = false;
        }

        if($is_only_text){
            if(Settings::get('app_publish_media_required', 0, true) == 1 && !$__MINI_GLOBAL_IS_ADMIN_SUPER__){
                return $this->fail(200001, [], '笔记需要带上视频或图片哦');
            }
        }
        if(Cache::has('lock:add:post:'.$uid)){
            return $this->fail(700003);
        }
        Cache::put('lock:add:post:'.$uid, 1, 60);
        $post_id = PostsRepositores::add($uid, $is_examine, $posts_title, $contents, $circle_id, $tags, $goods, $image_urls, $video_urls, $address, $videoThumbUrl, $video_width, $video_height, $votes, $file_list, $sounds_list, $pay_content_id, $__MINI_GLOBAL_DEVICE__, $refer_id, $contact_phone, $sph_obj, $useds, $bureaus, $is_anonymous, $voter_id);
        Cache::forget('lock:add:post:'.$uid);
        if ($post_id) {
            if(Settings::get('app_publish_frequency_min', 10, true) > 0){
                Cache::put('addPost:time:'.$__MINI_GLOBAL_TENANT_ID__.':'.$uid, 1, 60 * Settings::get('app_publish_frequency_min', 10, true));
            }
            if($circle_id){
                Cache::forget('circle:postCount:'.$circle_id);
                ForgetCircleUnreadCountJob::dispatch($circle_id);
                $online_user_ids = UserUtils::user_onlines(1);
                if($online_user_ids && is_array($online_user_ids)){
                    if($online_user_ids > 100){
                        $online_user_ids = WxUserCircle::whereIn('user_id', $online_user_ids)->where('circle_id', $circle_id)->where('user_circle_state', 0)->pluck('user_id')->toArray();
                    }
                    if($online_user_ids && is_array($online_user_ids)){
                        foreach ($online_user_ids as $online_user){
                            Cache::forget('user_circle_unread_count:'.$online_user);
                        }
                    }
                }
            }
            Cache::forget('user:post:count:'.$uid);
            // 视频封面
            if($video_urls && _empty_($videoThumbUrl)){
                VideoSnapshotJob::dispatch(WxPostsVideo::where('posts_id', $post_id)->value('id'));
            }
            UserUtils::add_user_experience($uid, 1);
            GatewayUtils::success('all', 6);
            CreatePostSyncJob::dispatch($post_id, $uid, $contents, $circle_id, $tags, $goods, $image_urls, $video_urls, $address, $videoThumbUrl, $video_width, $video_height);
            UserInputSafeCheckJob::dispatch($uid, $contents);
            Utils::image_state_change($image_state_change_list, 1);
            UserPublishedFollowJob::dispatch($uid, $circle_id, '')->delay(now()->addSeconds(5));
            // 机器人点赞
            CalculateLikesNumJob::dispatch($post_id);
            UpdatePostVideoIdJob::dispatch($post_id);
            UpdatePostTagIdJob::dispatch($post_id);
            CalculateFollowsNumJob::dispatch($uid);
            Redis::sadd('realtime:post:set', $post_id);
            UpdatePostOnlyTextJob::dispatch(0);
            if($circle_id > 0){
                ImitateCircleJoinStepJob::dispatch($circle_id, mini_rand(1, 100) <= 60 ? mini_rand(1, 2) : 0)->delay(now()->addMinutes(mini_rand(1, 20)));
            }

            // 订阅消息id
            $tmplIds = [];
            if($__MINI_GLOBAL_DEVICE__ == 'mp'){
                $comment_add_id = Settings::get('mini_template_message_comment_add', '');
                if(!_empty_($comment_add_id)){
                    $tmplIds[] = $comment_add_id;
                }
                $exceptional_id = Settings::get('mini_template_message_exceptional', '');
                if(!_empty_($exceptional_id)){
                    $tmplIds[] = $exceptional_id;
                }
                $beliked_id = Settings::get('mini_template_message_beliked', '');
                if(!_empty_($beliked_id)){
                    $tmplIds[] = $beliked_id;
                }
            }

            if($is_examine == 0){
                // 待审核
                //给对应圈子圈主发送待审核信息
                if($circle){
                    UserUtils::assistant_notice($circle['user_id'], '您创建的'.env('circle_call', '圈子').'「' . '<a href="/pages/circle/list?id='.$circle['id'].'">'.$circle['circle_name'].'</a>' . '」有一篇新的内容等待您去审核哦，请务必在24小时内进行处理。');
//                    UserUtils::assistant_notice('admin', '圈子「' . '<a href="/pages/circle/list?id='.$circle['id'].'">'.$circle['circle_name'].'</a>' . '」有一篇新的笔记等待您去审核哦！');
                    UserUtils::assistant_notice_review(101, $post_id);
                }else{
                    UserUtils::assistant_notice_review(101, $post_id);
                }
            }else{
                // 审核通过
                //给对应圈子圈主发送新内容信息
                if($circle){
                    UserUtils::assistant_notice($circle['user_id'], '您创建的'.env('circle_call', '圈子').'「' . '<a href="/pages/circle/list?id='.$circle['id'].'">'.$circle['circle_name'].'</a>' . '」有一篇新的内容发布，您要好好把关哦。');
                }
                _mini_aite($uid, $contents, 1, false, $post_id);
                $msg = UserUtils::reward_user_coin($uid, 'publish');
                if($msg){
                    UserUtils::assistant_notice($uid, '您发表的笔记(id:<a href="/pages/sticky/sticky?id='.$post_id.'">'.$post_id.'</a>)已经审核通过，并获得发布奖励：'.$msg);
                    return $this->success(['post_id'=>$post_id, 'tip'=>'发布成功', 'tmplIds'=>$tmplIds, 'reward_coin'=>$msg, 'ok'=> Settings::get('app_publish_success_popup', 0) == 1 ? 1 : 2, 'target_type' => -6, 'target_id' => '/pages/sticky/sticky?id='.$post_id, 'promotion' => $__MINI_GLOBAL_PAYCODE_5__ ? 1 : 0 ]);
                }else{
                    UserUtils::assistant_notice($uid, '您发表的笔记(id:<a href="/pages/sticky/sticky?id='.$post_id.'">'.$post_id.'</a>)已经审核通过');
                    return $this->success( ['post_id'=>$post_id, 'tip'=>'发布成功', 'tmplIds'=>$tmplIds, 'ok' => Settings::get('app_publish_success_popup', 0) == 1 ? 1 : 2, 'target_type' => -6, 'target_id' => '/pages/sticky/sticky?id='.$post_id, 'promotion' => $__MINI_GLOBAL_PAYCODE_5__ ? 1 : 0 ] );
                }
            }
            return $this->success( ['post_id'=>$post_id, 'tip'=>'我们会以最快的速度为您审贴', 'tmplIds'=>$tmplIds, 'ok' => 0, 'target_type' => -6, 'target_id' => '/pages/sticky/sticky?id='.$post_id, 'promotion' => $__MINI_GLOBAL_PAYCODE_5__ ? 1 : 0 ] );
        } else {
            if($pay_content_id > 0){
                WxPostsPayContent::where('id', $pay_content_id)->forceDelete();
            }
            return $this->fail(416001, $post_id);
        }

    }

    /**
     * 视频滑动
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function videoSlide(Request $request){
        $uid = $request->uid;
        $post_id = $request->firstVideo;
        $page = $request->page;
        $limit = $request->limit;

        global $__MINI_GLOBAL_PAYCODE_24__;
        if(!$__MINI_GLOBAL_PAYCODE_24__){
            return $this->fail(700000);
        }

        if(_empty_($limit)){
            $limit = 10;
        }else{
            $limit = _between_($limit, 1, 100);
        }

        _limit_user('video:slide', $uid, 30);
        $data = WxPost::has('video')->where('is_examine', 1)->where('posts_state', 0)->inRandomOrder()->simplePaginate($limit);
        if($data){

            PostUtils::reset_loop();
            $data->map(function ($v, $k) use ($uid){
                return PostUtils::defaultProcess($k, $v,75);
            });

            if($page == 1 && $post_id){
                $data2 = WxPost::where('id', $post_id)->get();
                $data2->map(function ($v, $k) use ($uid){
                    return PostUtils::defaultProcess($k, $v, 75);
                });
                $data = json_decode($data->toJson(), true);
                $data['data'] = $data2->concat($data['data']);
            }

            return $this->success($data);
        }else{
            return $this->fail(200003);
        }
    }

    /**
     * 点赞
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function like(Request $request)
    {
        $uid = $request->uid;
        $posts_id = $request->posts_id;
        if(_empty_($posts_id)){
            return $this->fail(200001);
        }

        $posts_id = _abs($posts_id);

        PostsRepositores::addLike($uid, $posts_id);
        return $this->success();
    }

    /**
     * 收藏
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function collect(Request $request)
    {
        $uid = $request->uid;
        $posts_id = $request->posts_id;
        if(_empty_($posts_id)){
            return $this->fail(200001);
        }

        $posts_id = _abs($posts_id);

        PostsRepositores::addCollect($uid, $posts_id);
        update_user_visit($uid, 1, $posts_id);
        return $this->success();
    }

    /** 图片不适
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function blur(Request $request){

        global $__MINI_GLOBAL_PAYCODE_0__;
        if(!$__MINI_GLOBAL_PAYCODE_0__){
            return $this->fail(700000);
        }

        $uid = $request->uid;
        $posts_id = $request->posts_id;
        if(_empty_($posts_id)){
            return $this->fail(200001);
        }
        $posts_id = _abs($posts_id);

        $post = WxPost::find($posts_id);
        if(_empty_($post)){
            return $this->fail(200003);
        }

        if(!is_object_user_special($uid, $post->tenant_id) && $post->user_id != $uid){
            return $this->fail(200000);
        }

        if(PostsRepositores::addBlur($posts_id)){
            return $this->success();
        }else{
            return $this->fail(200002);
        }
    }

    /** 移动圈子
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function move(Request $request){

        global $__MINI_GLOBAL_PAYCODE_0__;
        if(!$__MINI_GLOBAL_PAYCODE_0__){
            return $this->fail(700000);
        }

        $uid = $request->uid;
        $posts_id = $request->posts_id;
        $circle_id = $request->circle_id;
        if(_empty_($posts_id) || _empty_($circle_id)){
            return $this->fail(200001);
        }
        $posts_id = _abs($posts_id);
        $post = WxPost::find($posts_id);
        if(_empty_($post)){
            return $this->fail(200003);
        }
        if(!is_object_user_special($uid, $post->tenant_id)){
            return $this->fail(200000);
        }

        $user_name = WxUser::where('id', $uid)->value('user_name');

        $post_user_id = $post->user_id;
        $post_circle_id = $post->circle_id;
        $post_circle_name = $post->circle_name;

        $circle = WxCircle::find($circle_id);
        if($circle){
            WxPost::where('id', $posts_id)->update(['circle_id'=>$circle->id, 'circle_name'=>$circle->circle_name]);
            UpdateCommentCircleJob::dispatch([$posts_id]);
            Cache::forget('get_post_circle_user_id:'.$posts_id);
            UserUtils::add_user_notice(2002, $post_user_id, '笔记转移通知', '您的「<a href="/pages/sticky/sticky?id='.$post->id.'">笔记（id：'.$post->id.'）</a>」已被管理员「<a href="/pages/user/user?id='.$uid.'">'.$user_name.'</a>」从「<a href="/pages/circle/list?id='.$post_circle_id.'">'.$post_circle_name.'</a>」'.env('circle_call', '圈子').'转移到「<a href="/pages/circle/list?id='.$circle->id.'">'.$circle->circle_name.'</a>」圈子', 100);
            return $this->success();
        }else{
            return $this->fail(200003, [], '您选择的'.env('circle_call', '圈子').'不存在！');
        }
    }


    /** 笔记审核
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function examine(Request $request){
        $uid = $request->uid;
        $posts_id = $request->posts_id;
        global $__MINI_GLOBAL_TENANT_ID__;

        if(_empty_($posts_id)){
            return $this->fail(200001);
        }
        $posts_id = _abs($posts_id);

        $flag = false;
        $the_post = WxPost::find($posts_id);
        if(_empty_($the_post)){
            return $this->fail(200003);
        }
        $post_user_id = $the_post->user_id;
        $circle_user_id = PostUtils::get_post_circle_user_id($posts_id);
        $is_examine = $the_post->is_examine;

        if(is_object_user_special($uid, $the_post->tenant_id)){
            // 管理员特权
            $flag = true;
        }else if($circle_user_id == $uid){
            // 圈主特权
            $flag = true;
        }else if($the_post->user_id == $uid){
            // 已经通过状态下， 自己可以驳回
            if($is_examine == 1){
                $flag = true;
            }
        }

        if(!$flag){
            return $this->fail(200000);
        }

        $user_name = WxUser::where('id', $uid)->value('user_name');


        $call_name = '管理员';
        if($circle_user_id == $uid){
            $call_name = env('circle_user_call', '圈主');
        }else if($post_user_id == $uid){
            $call_name = '自己';
        }

        if($is_examine == 0 || $is_examine == 2){
            // 发送通知
            WxPost::where('id',$posts_id)->update(['is_examine'=>1]);
            UserUtils::assistant_notice($post_user_id, '审核通过，您发表的笔记(id:<a href="/pages/sticky/sticky?id='.$posts_id.'">'.$posts_id.'</a>)已被'.$call_name.'「<a href="/pages/user/user?id='.$uid.'">'.$user_name.'</a>」审核通过');
        }else{
            WxPost::where('id',$posts_id)->update(['is_examine'=>2]);
            if($post_user_id != $uid){
                UserUtils::assistant_notice($post_user_id, '您发表的笔记(id:<a href="/pages/sticky/sticky?id='.$posts_id.'">'.$posts_id.'</a>)被'.$call_name.'「<a href="/pages/user/user?id='.$uid.'">'.$user_name.'</a>」驳回了');
            }
        }

        return $this->success();
    }

    /** 置顶
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function sticky(Request $request){

        $uid = $request->uid;
        $posts_id = $request->posts_id;
        $scene = $request->scene;

        global $__MINI_GLOBAL_PAYCODE_0__, $__MINI_GLOBAL_IS_ADMIN_SUPER__;
        if(!$__MINI_GLOBAL_PAYCODE_0__ && $scene != 1){
            return $this->fail(700000);
        }

        if(_empty_($posts_id) || _empty_($scene)){
            return $this->fail(200001);
        }
        $posts_id = _abs($posts_id);

        if(!in_array($scene, [1, 5, 6, 8, 9, 10, 60001])){
            return $this->fail(200014);
        }

        // 权限验证
        // 圈主权限+管理员权限
        if($scene == 5 || $scene == 8){
            // 主页置顶
            $post_author = PostUtils::is_post_author($posts_id, $uid);
            if($post_author){

            }else{
                if(!$__MINI_GLOBAL_IS_ADMIN_SUPER__){
                    return $this->fail(200000);
                }
            }
        }else if($scene == 6 || $scene == 60001){
            // 管理员或圈子管理员
            $circle_id = WxPost::where('id', $posts_id)->value('circle_id');
            $the_circle = WxCircle::find($circle_id);
            if(_empty_($the_circle)){
                return $this->fail(200003);
            }
            // 不是管理 也不是圈主
            if(!is_object_user_special($uid, $the_circle->tenant_id) && $the_circle->user_id != $uid){
                return $this->fail(200000);
            }
        }else{
            if(!$__MINI_GLOBAL_IS_ADMIN_SUPER__){
                return $this->fail(200000);
            }
        }

        if(PostsRepositores::addSticky($scene, $posts_id)){
            return $this->success();
        }else{
            return $this->fail(200002);
        }
    }

    public function posts_process(Request $request){
        $type = _empty_default_($request->type, '');
        if ($type == 'delete') {
            return $this->deletePosts($request);
        }else if ($type == 'sticky') {
            // 置顶
            return $this->sticky($request);
        }else if ($type == 'examine') {
            // 笔记审核
            return $this->examine($request);
        }else if ($type == 'move') {
            // 移动圈子
            return $this->move($request);
        }else if ($type == 'blur') {
            // 图片不适
            return $this->blur($request);
        }else if ($type == 'collect') {
            // 收藏
            return $this->collect($request);
        }else if ($type == 'like') {
            // 喜欢
            return $this->like($request);
        }else if ($type == 'add') {
            // 发帖
            return $this->addPost($request);
        }else if ($type == 'echo') {
            // 编辑回显
            return $this->echoPost($request);
        }else if ($type == 'update') {
            // 更新
            return $this->updatePost($request);
        }else if ($type == 'limit') {
            return $this->limit($request);
        }else if ($type == 'promotion_refresh_list') {
            return $this->promotion_refresh_list($request);
        }else if ($type == 'promotion_refresh_stop') {
            return $this->promotion_refresh_stop($request);
        }else if ($type == 'promotion_coin_pay') {
            return $this->promotion_coin_pay($request);
        }
    }

    private function promotion_coin_pay(Request &$request){
        $uid = $request->uid;
        $is_promotion_refresh = false;
        $post_id = _abs(_empty_default_($request->post_id, 0));
        if(_empty_($post_id)){
            return $this->fail(200004);
        }
        $time_list = _empty_default_($request->time_list, []);
        $index_option = _empty_default_($request->index, 0);
        if(_empty_default_($request->is_refresh, 0) == 1){
            if(_empty_($time_list)){
                return $this->fail(200004);
            }
            $is_promotion_refresh = true;
        }else{
            if(_empty_($index_option, true)){
                return $this->fail(200004);
            }
        }
        $the_post = WxPost::where('id', $post_id)->where([['is_examine' ,'=', 1], ['posts_state' , '=', 0]])->first();
        if(!$the_post){
            DB::rollBack();
            return $this->fail(200004, [], '笔记不存在或非正常推送状态');
        }

        if($is_promotion_refresh){
            if(!is_array($time_list)){
                return $this->fail(200004);
            }
            $the_order_price = bcdiv(Settings::get('app_promoted_post_refresh_cost', 1.0, true) * count($time_list), 1, 2);
            $order_info_des = '笔记推广自动刷新'.count($time_list).'次';
        }else{

            global $__MINI_GLOBAL_TENANT_ID__;
            $tmp_tenant_id = -1;
            if($__MINI_GLOBAL_TENANT_ID__ != $the_post->tenant_id){
                $tmp_tenant_id = $__MINI_GLOBAL_TENANT_ID__;
                $__MINI_GLOBAL_TENANT_ID__ = $the_post->tenant_id;
            }
            $post_options = Settings::get('app_promoted_post_options', [], true);
            if($tmp_tenant_id > 0){
                $__MINI_GLOBAL_TENANT_ID__ = $tmp_tenant_id;
            }



            if(_empty_($post_options) || !isset($post_options[$index_option])){
                DB::rollBack();
                return $this->fail(200004, [], '后台未配置index为'.$index_option.'的付费推广套餐');
            }
            $the_option = $post_options[$index_option];
            if($the_option['credit_type'] != 1){
                DB::rollBack();
                return $this->fail(200004, [], '该接口只能进行余额付费推广');
            }
            $the_order_price = $the_option['price'];
            $order_info_des = '笔记付费置顶'.$the_option['hour'].'小时';
        }

        $app_coin_pay_rate = Settings::get('app_coin_pay_rate', 100);
        $order_coins_num = (int)($app_coin_pay_rate * $the_order_price);

        DB::beginTransaction();
        try {
            // todo:
            if($is_promotion_refresh){
                $pay_res2 = UserUtils::update_user_coins($uid, 3, -$order_coins_num, '笔记(id: '.$post_id.')付费推广自动刷新'.count($time_list).'次（'. $order_coins_num. Settings::get('app_coin_name', '硬币') . '抵扣了￥'.$the_order_price.'）：金币-'.$order_coins_num);
                if($pay_res2){

                    $insert_data = [];
                    sort($time_list);
                    foreach ($time_list as $timestap){
                        $insert_data[] = [
                            'user_id' => $uid,
                            'post_id' => $post_id,
                            'expect_time' => Carbon::createFromTimestamp((int)($timestap / 1000)),
                            'refresh_time' => null,
                            'balance_cost' => 0,
                            'coin_cost' => (int)($order_coins_num / count($time_list)),
                            'status' => 0
                        ];
                    }
                    WxPostsWeightRefresh::insert($insert_data);

                }else{
                    DB::rollBack();
                    return $this->fail(200011, [], Settings::get('app_coin_name', '硬币').'不足');
                }
            }else{
                $pay_res2 = UserUtils::update_user_coins($uid, 3, -$order_coins_num, '笔记(id: '.$post_id.')付费推广'.$the_option['tip'].'（'. $order_coins_num. Settings::get('app_coin_name', '硬币') . '抵扣了￥'.$the_order_price.'）：金币-'.$order_coins_num);
                if($pay_res2){

                    $the_weight = $the_post->weight;
                    if($the_weight < time()){
                        $the_weight = time();
                    }
                    $the_weight += $the_option['hour'] * 3600;

                    WxPost::withoutSyncingToSearch(function () use ($post_id, $the_weight) {
                        WxPost::where('id', $post_id)->update(['weight'=>timetostr($the_weight)]);
                    });

                }else{
                    DB::rollBack();
                    return $this->fail(200011, [], Settings::get('app_coin_name', '硬币').'不足');
                }
            }
            DB::commit();
            return $this->success();
        } catch (\Exception $e) {
            DB::rollBack();
            _logger_(__file__, __line__, $e->getMessage());
            return $this->fail(200002);
        }
    }

    private function promotion_refresh_stop(Request &$request){
        $uid = $request->uid;
        $posts_id = _abs(_empty_default_($request->posts_id, 0));
        if(_empty_($posts_id) || _empty_($uid)){
            return $this->fail(200001);
        }
        $the_post = WxPost::find($posts_id);
        if(_empty_($the_post)){
            return $this->fail(200003);
        }
        if($uid != $the_post->user_id && !is_object_user_special($uid, $the_post->tenant_id)){
            return $this->fail(200000);
        }

        $ids = [];
        $coin_total = 0;
        $balance_total = 0;
        $data = WxPostsWeightRefresh::where('user_id', $uid)->where('post_id', $posts_id)->where('status', 0)->get()->toArray();
        if(_empty_($data)){
            return $this->fail(200004, [], '已全部推广完成，无法中断');
        }
        foreach ($data as $item){
            $ids[] = $item['id'];
            $coin_total += $item['coin_cost'];
            $balance_total += $item['balance_cost'];
        }

        $coin_total = (int)($coin_total * 0.7);
        $balance_total = floor(($balance_total * 0.7 * 100)) / 100;

        DB::beginTransaction();
        try {
            // todo:
            WxPostsWeightRefresh::whereIn('id', $ids)->delete();
            if($coin_total > 0){
                UserUtils::update_user_coins($uid, 4, $coin_total, '收到「笔记 id: '.$the_post->id.'」自动刷新订单的金币抵扣退款' . Settings::get('app_coin_name', '硬币') . $coin_total);
            }
            if($balance_total >= 0.01){
                UserUtils::update_user_financial($uid, 33, $balance_total, '收到「<a href="/pages/sticky/sticky?id='.$the_post->id.'">笔记 id: '.$the_post->id.'</a>」自动刷新订单的退款，扣掉平台分成30%，您获得'.$balance_total.'余额。');
            }
            DB::commit();
            return $this->success();
        } catch (\Exception $e) {
            DB::rollBack();
            _logger_(__file__, __line__, $e->getMessage());
            return $this->fail(200006);
        }
    }

    private function promotion_refresh_list(Request &$request){
        $uid = $request->uid;
        $posts_id = _abs(_empty_default_($request->posts_id, 0));
        if(_empty_($posts_id) || _empty_($uid)){
            return $this->fail(200001);
        }
        $the_post = WxPost::find($posts_id);
        if(_empty_($the_post)){
            return $this->fail(200003);
        }
        if($uid != $the_post->user_id && !is_object_user_special($uid, $the_post->tenant_id)){
            return $this->fail(200000);
        }
        $data = WxPostsWeightRefresh::where('post_id', $posts_id)->orderBy('expect_time', 'asc')->get()->toArray();
        if(_empty_($data)){
            return $this->fail(200003);
        }

        $rest = 0;
        foreach ($data as $item){
            if($item['status'] === 0){
                $rest += 1;
            }
        }

        return $this->success(['list'=>$data, 'rest' => $rest, 'ok_count'=> count($data) - $rest, 'cancel' => ($the_post->user_id == $uid ? 1 : 0)]);
    }

    private function limit(Request &$request){
        $uid = $request->uid;
        $posts_id = _abs(_empty_default_($request->posts_id, 0));
        $days = _abs(_empty_default_($request->days, 1));
        $the_post = WxPost::find($posts_id);
        if(_empty_($the_post)){
            return $this->fail(200003);
        }
        if(!is_object_user_special($uid, $the_post->tenant_id)){
            return $this->fail(200000);
        }

        $weight = $the_post->weight;
        if($weight > time()){
            $weight = time();
        }
        $weight -= 86400 * $days;

        WxPost::withoutSyncingToSearch(function () use (&$the_post,$weight){
            WxPost::where('id', $the_post->id)->update(['weight'=>timetostr($weight)]);
        });

//        UserUtils::assistant_notice($the_post->user_id, '您发表的「<a href="/pages/sticky/sticky?id='.$the_post->id.'">笔记 id:'.$the_post->id.'</a>」被管理员「<a href="/pages/user/user?id='.$uid.'">'.UserUtils::get_cached_user_name($uid).' id:'.$uid.'</a>」首页限流');

        return $this->success();
    }

    private function echoPost(Request &$request){
        $uid = $request->uid;
        $posts_id = $request->posts_id;
        $editor_name = _empty_default_($request->editor_name, 'default');

        $the_post = WxPost::find($posts_id);
        if(_empty_($the_post)){
            return $this->fail(200003);
        }

        // 权限验证
        if(!is_object_user_special($uid, $the_post->tenant_id) && $the_post->user_id != $uid){
            return $this->fail(200000);
        }


        $the_post->posts_content_raw =html_entity_decode( _mini_phone(_mini_aite_replace(_mini_emoji($the_post->posts_content, true), true)) );

        if($the_post->circle_id > 0){
            $the_circle = WxCircle::find($the_post->circle_id);
        }

        if($the_post->video_id === Null){
            $the_post->video = WxPostsVideo::where('posts_id', $the_post->id)->first();//视频
            UpdatePostVideoIdJob::dispatch($the_post->id);
        }else if($the_post->video_id > 0){
            $the_post->video = WxPostsVideo::where('id', $the_post->video_id)->first();//视频
        }else if($the_post === 0){
            $the_post->video = null;
        }

        if($the_post->is_wechat_sph){
            $the_post->wechat_sph = get_post_meta($the_post->id, 'wechat_sph', 'j');
        }

        if(!_empty_($the_post->useds)){
            $the_post->used_goods = WxUsedGood::whereIn('id', $the_post->useds)->orderBy(DB::raw('FIND_IN_SET(id, "' . implode(",", $the_post->useds) . '"' . ")"))->get();
            if($the_post->used_goods){
                $the_post->used_goods->map(function ($used_good){

                    if($used_good->image_urls){
                        $used_good->pic = _array_key($used_good->image_urls[0], 'url', '') . '?imageMogr2/thumbnail/600x/format/webp/interlace/1';
                        $used_good->pic_width = _array_key($used_good->image_urls[0], 'width', '');
                        $used_good->pic_height = _array_key($used_good->image_urls[0], 'height', '');
                        if($used_good->pic_width >= 0){
                            $old_widht = $used_good->pic_width;
                            $used_good->pic_width = 363;
                            $used_good->pic_height = (int)( (363 * $used_good->pic_height) / $old_widht );
                        }
                    }

                    $used_good->needed_count = WxUsedNeed::where('used_good_id', $used_good->id)->where('status', 1)->count();
                    if(_empty_($used_good->needed_count)){
                        $used_good->needed_count = 0;
                    }

                    return $used_good;
                });
            }
        }

        if( !_empty_($the_post->tags_id) ){
            $the_post->tags = WxTag::whereIn('id', explode(',', $the_post->tags_id))->get(['tags_name', 'id']);
        }else if($the_post->tags_id === ''){
            $the_post->tags = null;
        }else if($the_post->tags_id === '0'){
            $the_post->tags = PostsRepositores::getPostTags($the_post->id);
            UpdatePostTagIdJob::dispatch($the_post->id);
        }

        if( !_empty_($the_post->goods_id) ){
            $the_post->goods = WxShopGoods::whereIn('id', explode(',', $the_post->goods_id))->get(['id', 'pic', 'name', 'credit_type', 'intro', 'price', 'vip_price', 'tk_platform_id', 'buys']);
        }else if($the_post->goods_id === ''){
            $the_post->goods = null;
        }else if($the_post->goods_id === '0'){
            $the_post->goods = PostsRepositores::getPostGoods($the_post->id);
            UpdatePostGoodsIdJob::dispatch($the_post->id);
        }

        if( !_empty_($the_post->sounds_id) ){
            $the_post->sounds = WxPostsSound::whereIn('id', explode(',', $the_post->sounds_id))->get();
        }else if($the_post->sounds_id === ''){
            $the_post->sounds = null;
        }else if($the_post->sounds_id === '0'){
            $the_post->sounds = PostsRepositores::getPostSounds($the_post->id);
            UpdatePostSoundsIdJob::dispatch($the_post->id);
        }

        $address_obj = [];
        if($the_post->address_id > 0){
            $address_obj = WxPostsAddress::where('id', $the_post->address_id)->first();
        }

        $pay_content_obj_ = [];
        if($the_post->pay_content_id > 0){
            $pay_content_obj_ = WxPostsPayContent::find($the_post->pay_content_id);
        }

        if(!_empty_($the_post->bureaus)){
            $the_post->bureau_list = WxBureau::whereIn('id', $the_post->bureaus)->orderBy(DB::raw('FIND_IN_SET(id, "' . implode(",", $the_post->bureaus) . '"' . ")"))->get();
            if($the_post->bureau_list){
                $the_post->bureau_list->map(function ($wxBureau){
                    global $__MINI_GLOBAL_CURRENT_USER_ID__;
                    if($wxBureau->image_urls){
                        $wxBureau->pic = _array_key($wxBureau->image_urls[0], 'url', '') . '?imageMogr2/thumbnail/600x/format/webp/interlace/1';

                        $wxBureau->pic_width = _array_key($wxBureau->image_urls[0], 'width', '');
                        $wxBureau->pic_height = _array_key($wxBureau->image_urls[0], 'height', '');

                        if($wxBureau->pic_width >= 0){
                            $old_widht = $wxBureau->pic_width;
                            $wxBureau->pic_width = 363;
                            $wxBureau->pic_height = (int)( (363 * $wxBureau->pic_height) / $old_widht );
                        }
                    }
                    if(_empty_($wxBureau->distance)){
                        if($__MINI_GLOBAL_CURRENT_USER_ID__ > 0){
                            $wxBureau->distance = UserUtils::distance($__MINI_GLOBAL_CURRENT_USER_ID__, $wxBureau->longitude, $wxBureau->latitude);
                        }
                    }

                    if($wxBureau->distance && $wxBureau->distance > 0){
                        if($wxBureau->distance < 10){
                            $wxBureau->distance = '<10m';
                            $wxBureau->distance_name = $wxBureau->district;
                        }else if($wxBureau->distance >= 1000 && $wxBureau->distance <= 200000){
                            $wxBureau->distance = '<'. round($wxBureau->distance / 1000, 2).'km';
                            $wxBureau->distance_name = $wxBureau->city;
                        }else if($wxBureau->distance > 200000){
                            $wxBureau->distance = round($wxBureau->distance / 1000, 2).'km';
                            $wxBureau->distance_name = $wxBureau->province;
                        }else{
                            $wxBureau->distance = '<'.(int)$wxBureau->distance.'m';
                            $wxBureau->distance_name = $wxBureau->district;
                        }
                    }else{
                        $wxBureau->distance = '';
                        $wxBureau->distance_name = $wxBureau->district;
                    }
                    return $wxBureau;
                });
            }
        }

        if( !_empty_($the_post->files_id) ){
            $the_post->files = WxPostsFile::whereIn('id', explode(',', $the_post->files_id))->get();
        }else if($the_post->files_id === ''){
            $the_post->files = null;
        }else if($the_post->files_id === '0'){
            $the_post->files = PostsRepositores::getPostFiles($the_post->id);
            UpdatePostFilesIdJob::dispatch($the_post->id);
        }

        if($the_post->has_fields === 1) {
            $the_post->fields = WxPostsField::find($the_post->id);
        }else if($the_post->has_fields === null){
            $the_post->fields = WxPostsField::find($the_post->id);
            UpdatePostFieldsJob::dispatch($the_post->id);
        }

        if($editor_name == 'default'){
            $selectUseds = [];
            $post_type = PostUtils::post_type($the_post);
            if($post_type == 'single'){

            }else{
                $the_post->posts_content_raw = str_replace(['<br>', '<br/>'], "\n", $the_post->posts_content_raw);
            }
            $circle = [
                'id' => 0,
                'circle_name' => ''
            ];
            $tags = [];
            $goods = [];
            $address = [];

            if($address_obj){
                $address['latitude'] = $address_obj->latitude;
                $address['longitude'] = $address_obj->longitude;
                $address['address_name'] = $address_obj->address_name;
                $address['address_detailed'] = $address_obj->address_detailed;
            }


            if(!_empty_($the_post->tags)){
                $the_post->tags->map(function ($tag_obj) use (&$tags){
                    $tags[] = [
                        'id' => $tag_obj->id,
                        'tags_name' => $tag_obj->tags_name
                    ];
                });
            }

            if($the_post->circle_id > 0){
                $circle = [
                    'id' => $the_circle->id,
                    'circle_name' => $the_circle->circle_name
                ];
            }


            $image_urls = [];
            WxPostsImg::where('posts_id', $the_post->id)->get(['id','img_url', 'posts_id','width', 'height'])->map(function ($img_obj) use (&$image_urls){
                $image_urls[] = [
                    'url' => $img_obj->img_url
                ];
            });

            // 处理二手
            if($the_post->used_goods){
                $the_post->used_goods->map(function ($used_good) use (&$selectUseds){
                    $selectUseds[] = [
                        'id' => $used_good->id,
                        'pic' => $used_good->pic,
                        'title' => $used_good->title,
                        'price' => $used_good->price,
                        'needed_count' => $used_good->needed_count,
                    ];
                });
            }


            if($the_post->goods){
                $the_post->goods->map(function ($good_obj) use (&$goods){
                    $goods[] = [
                        'id' => $good_obj->id,
                        'name' => $good_obj->name,
                        'pic' => $good_obj->pic ? $good_obj->pic[0] : []
                    ];
                });
            }



            $pay_content_obj = [
                'words_percent' => 100,
                'is_file' => 0,
                'is_img' => 0,
                'is_video' => 0,
                'credit_type' => 0,
                'hidden' => '',
                'price' => 0,
                'id' => 0
            ];
            if($pay_content_obj_ && $pay_content_obj_->id > 0){
                $pay_content_obj['id'] = $pay_content_obj_->id;
                $pay_content_obj['words_percent'] = $pay_content_obj_->words_percent;
                $pay_content_obj['is_file'] = $pay_content_obj_->is_file;
                $pay_content_obj['is_img'] = $pay_content_obj_->is_img;
                $pay_content_obj['is_video'] = $pay_content_obj_->is_video;
                $pay_content_obj['credit_type'] = $pay_content_obj_->credit_type;
                $pay_content_obj['hidden'] = $pay_content_obj_->hidden;
                $pay_content_obj['price'] = $pay_content_obj_->price;
            }


            $video_url = '';
            $video_thumb_url = '';
            $video_height = 0;
            $video_width = 0;
            if($the_post->video){
                $video_url = $the_post->video->video_url;
                $video_thumb_url = $the_post->video->video_thumb_url;
                $video_height = $the_post->video->video_height;
                $video_width = $the_post->video->video_width;
            }


            $selectBureaus = [];
            if($the_post->bureau_list){
                $the_post->bureau_list->map(function ($wxBureau) use (&$selectBureaus){
                    $selectBureaus[] = [
                        'id' => $wxBureau->id,
                        'pic' => $wxBureau->pic,
                        'title' => $wxBureau->title,
                        'least_price_tip' => $wxBureau->least_price_tip,
                        'service_date_start' => $wxBureau->service_date_start,
                        'service_time_start' => $wxBureau->service_time_start,
                        'address_detailed' => $wxBureau->address_detailed,
                        'distance' => $wxBureau->distance
                    ];
                });
            }

            $sph_video_feed_token = '';
	        $sph_image_urls = [];
            if($the_post->wechat_sph && _array_key($the_post->wechat_sph, 'feed_token', '')){
                $sph_video_feed_token = $the_post->wechat_sph['feed_token'];
                $sph_image_urls = [['url'=>$the_post->wechat_sph['img']]];
            }


            $upload_files = [];
            if($the_post->files){
                $the_post->files->map(function ($file_obj) use (&$upload_files){
                    $upload_files[] = [
                        'id' => $file_obj->id,
                        'name' => $file_obj->name
                    ];
                });
            }

            $sounds_files = [];
            if($the_post->sounds){
                $the_post->sounds->map(function ($sound_obj) use (&$sounds_files){
                    $sounds_files[] = [
                        'id' => $sound_obj->id,
                        'name' => $sound_obj->name
                    ];
                });
            }


            $contact_phone = '';
            if($the_post->fields){
                $contact_phone = $the_post->fields->contact_phone;
            }

            $selectVoter = null;
            if($the_post->voter_id > 0){
                $selectVoter = WxVoter::where('id', $the_post->voter_id)->first(['id', 'user_id', 'master_user_avatar', 'master_user_name', 'title', 'banners']);
            }

            return $this->success([
                'id' => $the_post->id,
                'editer' => $post_type == 'single' ? 'imagetext' : 'simple',
                'posts_title' => $the_post->posts_title,
                'imagetext_content' => $post_type == 'single' ? $the_post->posts_content_raw : '',
                'textinput' => $post_type == 'single' ? '' : $the_post->posts_content_raw,
                'selectUseds' => $selectUseds,
                'image_urls' => $image_urls,
                'circle' => $circle,
                'tags' => $tags,
                'goods' => $goods,
                'location' => $address,
                'pay_content_obj' => $pay_content_obj,

                'video_url' => $video_url,
                'video_thumb_url' => $video_thumb_url,
                'video_height' => $video_height,
                'video_width' => $video_width,
                'selectBureaus' => $selectBureaus,

                'sph_video_feed_token' => $sph_video_feed_token,
                'sph_image_urls' => $sph_image_urls,

                'upload_files' => $upload_files,
                'sounds_files' => $sounds_files,

                'contact_phone' => $contact_phone,
                'is_anonymous' => $the_post->is_anonymous,

                'selectVoter' => $selectVoter
            ]);

        }
    }

    /**
     * 删除
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function deletePosts(Request $request)
    {
        $uid = $request->uid;
        $posts_id = $request->posts_id;
        global $__MINI_GLOBAL_TENANT_ID__, $__MINI_GLOBAL_IS_ADMIN_SUPER__;

        if(_empty_($posts_id)){
            return $this->fail(200001);
        }
        $posts_id = _abs($posts_id);

        $flag = false;
        $the_post = WxPost::find($posts_id);
        if(_empty_($the_post)){
            return $this->fail(200003);
        }

        if(is_object_user_special($uid, $the_post->tenant_id)){
            // 管理特权
            $flag = true;
        }else if(PostUtils::get_post_circle_user_id($posts_id) == $uid){
            // 圈主特权
            $flag = true;
        }else if($the_post->user_id == $uid){
            // 自己删除
            $flag = true;
        }

        if(!$flag){
            return $this->fail(200000);
        }

        $r = PostsRepositores::deletePosts($posts_id, $the_post->user_id == $uid ? 1 : 2);
        if($r){
            if($the_post->circle_id){
                Cache::forget('circle:postCount:'.$the_post->circle_id);
                ForgetCircleUnreadCountJob::dispatch($the_post->circle_id);
            }
            // todo: 修改图片状态
            return $this->success();
        }else{
            return $this->fail(200002);
        }
    }

    /**
     * 关注用户
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function followUser(Request $request)
    {
        $uid = $request->uid;

        _limit_user('follow:user', $uid, 20);

        $user_follow_id = $request->posts_user_id;
        if(_empty_($user_follow_id)){
            return $this->fail(200001);
        }
        $res = UserUtils::follow_user($uid, $user_follow_id);
        if($res['code'] == 1){
            return $this->success([], $res['message']);
        }else{
            return $this->fail($res['message']);
        }
    }

    /**
     * 笔记详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function postsDetail(Request $request)
    {
        $uid = $request->uid;
        $posts_id = $request->posts_id;
        if(_empty_($posts_id)){
            return $this->fail(200001);
        }
        try{
            $posts_id = _abs($posts_id);
        }catch (\Exception $e){
            _logger_(__file__, __line__, $e->getMessage().'||||'.$posts_id);
            return $this->fail(200004);
        }

        $data = (new Model())->where('id', $posts_id)->get();
        if($data->isEmpty()){
            return $this->fail(200003);
        }
        $the_post = $data->get(0);

        // 锁定或下架
        if($the_post->posts_state == 1 || $the_post->posts_state == 2){
            // 已经下架了
            return $this->fail(416005);
        }

        // 待审或驳回
        if($the_post->is_examine == 0 || $the_post->is_examine == 2){
            if($uid == $the_post->user_id || is_object_user_special($uid, $the_post->tenant_id) || PostUtils::get_post_circle_user_id($posts_id) == $uid){

            }else{
                if($the_post->is_examine == 0){
                    // 待审核
                    return $this->fail(416006);
                }else{
                    // 被驳回
                    $overrule_content = '笔记被驳回！无法查看';
                    if($the_post->overrule_content){
                        $overrule_content = '笔记被驳回，'.$the_post->overrule_content;
                    }
                    return $this->fail(416007, [], $overrule_content);
                }
            }
        }

        if($data){
            $data = PostsRepositores::postsParame($data, $uid, 9);//文章详情
            if($uid > 0){
                update_user_visit($uid, 1, $posts_id);
            }
            return $this->success($data);
        }

        return $this->fail(200003);
    }

    /**
     * 相关笔记
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function postsRelevant(Request $request){
        $posts_id = $request->posts_id;
        $uid = $request->uid;
        if(_empty_($posts_id)){
            return $this->fail(200001);
        }
        $posts_id = _abs($posts_id);
        if(!SearchUtils::is_use_es()){
            return $this->fail(700000);
        }
        $data = PostsRepositores::relevantPosts($posts_id, $uid);
        if($data){
            return $this->success($data);
        }else{
            return $this->fail(200003);
        }
    }

    /**
     * 通过圈子获取笔记
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function postsByCircle(Request $request)
    {
        global $__MINI_GLOBAL_SCENE__;
        $circle_id = _abs($request->circle_id);
        $type = $request->type;
        $limit = $request->input('limit', 10);
        $uid = $request->uid;
        $page = $request->page;
        $tags = _empty_default_($request->tags, null);
        $sort = _empty_default_($request->sort, 0);
        $city = _empty_default_($request->city, '');

        if(_empty_($city) || $city == '全国' || $city == '重新定位' || $city == '定位中'){
            $city = '';
        }

        $is_tenant = _empty_default_($request->isTenant, 0);
        if(_empty_($is_tenant)){
            $is_tenant = false;
        }else{
            if($is_tenant == 2){
                if($__MINI_GLOBAL_SCENE__ == 6){
                    $is_tenant = Cache::remember('circle:default:is:tenant:'.$circle_id, 36000, function () use (&$circle_id){
                            $circle = WxCircle::find($circle_id);
                            if($circle){
                                if($circle->tenant_show == -1 && $circle->is_tenant_select == 1){
                                    return 1;
                                }
                            }
                            return 0;
                        }) == 1;
                }else{
                    $is_tenant = false;
                }
            }else{
                $is_tenant = true;
            }
        }
        if(!in_array($sort, [0, 1, 2])){
            $sort = 0;
        }
        if(!is_array($tags)){
            $tags = json_decode($tags, true);
        }
        if(_empty_($tags)){
            $tags = null;
        }
        return $this->success(PostsRepositores::postsByCircleId($circle_id, $type, $limit, $uid, $page, $tags, $sort, $city, $is_tenant));
    }

    /**
     * 通过话题获取笔记列表（瀑布流用）
     * @param Request $request
     */
    public function listByTagId(Request $request)
    {
        $tagId = $request->tag_id;
        $page = $request->page;
        $limit = 10;
        $uid = $request->uid;
        global $__MINI_GLOBAL_PAYCODE_12__, $__MINI_GLOBAL_PAYCODE_5__,$__MINI_GLOBAL_TENANT_ID__,$__MINI_GLOBAL_DEVICE__,$__MINI_GLOBAL_MODE__;
        // 获取全部笔记
        if (_empty_($tagId)) {
            if($__MINI_GLOBAL_PAYCODE_12__){
                $query = WxPost::where([['is_examine' ,'=', 1], ['posts_state' , '=', 0], ['img_count', '>', 0 ]]);
                $query = $query->where('tenant_id', $__MINI_GLOBAL_TENANT_ID__);

                // 控制视频隐藏
                if($__MINI_GLOBAL_DEVICE__ != 'mp'){
                    global $__MINI_GLOBAL_FRONT_VERSION__;
                    // todo: 临时
                    if($__MINI_GLOBAL_FRONT_VERSION__ >= '1.2.2.24'){

                    }else {
                        $query = $query->where('is_wechat_sph', 0);
                    }
                }
                if($__MINI_GLOBAL_MODE__ == 'examine'){
                    $query = $query->where('post_type', '<>', 'video');
                }

                $data = $query->orderBy('degree', 'desc')->simplePaginate($limit);
            }else{
                $query = WxPost::where([['is_examine' ,'=', 1], ['posts_state' , '=', 0], ['img_count', '>', 0 ]]);
                $query = $query->where('tenant_id', $__MINI_GLOBAL_TENANT_ID__);

                // 控制视频隐藏
                if($__MINI_GLOBAL_DEVICE__ != 'mp'){
                    global $__MINI_GLOBAL_FRONT_VERSION__;
                    // todo: 临时
                    if($__MINI_GLOBAL_FRONT_VERSION__ >= '1.2.2.24'){

                    }else {
                        $query = $query->where('is_wechat_sph', 0);
                    }
                }
                if($__MINI_GLOBAL_MODE__ == 'examine'){
                    $query = $query->where('post_type', '<>', 'video');
                }

                $data = $query->orderBy('id', 'desc')->simplePaginate($limit);
            }
        }else{
            if($__MINI_GLOBAL_PAYCODE_5__){
                $postIdsArr = WxPostsTag::where('tags_id', $tagId)->pluck('posts_id');
                $query = WxPost::whereIn('id', $postIdsArr)->where([['is_examine' ,'=', 1], ['posts_state' , '=', 0], ['img_count', '>', 0 ]]);
                $query = $query->where('tenant_id', $__MINI_GLOBAL_TENANT_ID__);

                // 控制视频隐藏
                if($__MINI_GLOBAL_DEVICE__ != 'mp'){
                    global $__MINI_GLOBAL_FRONT_VERSION__;
                    // todo: 临时
                    if($__MINI_GLOBAL_FRONT_VERSION__ >= '1.2.2.24'){

                    }else {
                        $query = $query->where('is_wechat_sph', 0);
                    }
                }
                if($__MINI_GLOBAL_MODE__ == 'examine'){
                    $query = $query->where('post_type', '<>', 'video');
                }

                $data = $query->orderBy('weight', 'desc')->simplePaginate($limit);
            }else{
                $postIdsArr = WxPostsTag::where('tags_id', $tagId)->pluck('posts_id');
                $query = WxPost::whereIn('id', $postIdsArr)->where([['is_examine' ,'=', 1], ['posts_state' , '=', 0], ['img_count', '>', 0 ]]);
                $query = $query->where('tenant_id', $__MINI_GLOBAL_TENANT_ID__);

                // 控制视频隐藏
                if($__MINI_GLOBAL_DEVICE__ != 'mp'){
                    global $__MINI_GLOBAL_FRONT_VERSION__;
                    // todo: 临时
                    if($__MINI_GLOBAL_FRONT_VERSION__ >= '1.2.2.24'){

                    }else {
                        $query = $query->where('is_wechat_sph', 0);
                    }
                }
                if($__MINI_GLOBAL_MODE__ == 'examine'){
                    $query = $query->where('post_type', '<>', 'video');
                }

                $data = $query->orderBy('id', 'desc')->simplePaginate($limit);
            }

        }
        PostUtils::reset_loop();
        $data->map(function ($v, $k) use ($uid){
            return PostUtils::WaterfallProcess($k, $v,19);
        });
        return $this->success($data);


    }

    /**
     * 通过话题获取笔记列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function listByTagIdV2(Request $request)
    {
        $tagId = $request->tag_id;
        $page = $request->page;
        $limit = 6;
        $uid = $request->uid;
        $sort_by = _empty_default_($request->sort_by, 'id');
        if(!in_array($sort_by, ['id', 'hot'])){
            return $this->fail(200004);
        }
        global $__MINI_GLOBAL_DEVICE__,$__MINI_GLOBAL_MODE__,$__MINI_GLOBAL_SCENE__,$__MINI_GLOBAL_TENANT_ID__;
        $is_tenant = _empty_default_($request->isTenant, false);
        if(_empty_($is_tenant)){
            $is_tenant = false;
        }else{
            $is_tenant = true;
        }
        // 获取全部笔记
        if (_empty_($tagId)) {
            $data = (new Model())
                ->where('is_examine', 1)
                ->where('posts_state', 0);

            if($is_tenant){
                $data = $data->where('tenant_id', $__MINI_GLOBAL_TENANT_ID__);
            }

            $not_like_post_set = get_user_meta($uid, 'feedback:notlike:post:set', 'j');
            $not_like_user_set = get_user_meta($uid, 'feedback:notlike:user:set', 'j');

            if(!_empty_($not_like_user_set)){
                $data = $data->whereNotIn('user_id', $not_like_user_set);
            }
            if(!_empty_($not_like_post_set)){
                $data = $data->whereNotIn('id', $not_like_post_set);
            }

            // 控制视频隐藏
            if($__MINI_GLOBAL_DEVICE__ != 'mp'){
                global $__MINI_GLOBAL_FRONT_VERSION__;
                // todo: 临时
                if($__MINI_GLOBAL_FRONT_VERSION__ >= '1.2.2.24'){

                }else {
                    $data = $data->where('is_wechat_sph', 0);
                }
            }
            if($__MINI_GLOBAL_MODE__ == 'examine'){
                $data = $data->where('post_type', '<>', 'video');
            }

            if($sort_by == 'id'){
                $data = $data->orderBy('id', 'desc');
            }else if($sort_by == 'hot'){
                $data = $data->orderBy('degree', 'desc')->orderBy('id', 'desc');
            }

            $data = $data->simplePaginate($limit);

            if($is_tenant){
                PostUtils::$force_show_multi_site = false;
            }
            $data = PostsRepositores::postsParame($data, $uid);//文章详情

            return $this->success($data);
        }
        $postIdsArr = WxPostsTag::where('tags_id', $tagId)->pluck('posts_id');
        $data = (new Model())
            ->where('is_examine', 1)
            ->where('posts_state', 0)
            ->whereIn('id', $postIdsArr);

        if($is_tenant){
            $data = $data->where('tenant_id', $__MINI_GLOBAL_TENANT_ID__);
        }

        $not_like_post_set = get_user_meta($uid, 'feedback:notlike:post:set', 'j');
        $not_like_user_set = get_user_meta($uid, 'feedback:notlike:user:set', 'j');

        if(!_empty_($not_like_user_set)){
            $data = $data->whereNotIn('user_id', $not_like_user_set);
        }
        if(!_empty_($not_like_post_set)){
            $data = $data->whereNotIn('id', $not_like_post_set);
        }

        // 控制视频隐藏
        if($__MINI_GLOBAL_DEVICE__ != 'mp'){
            global $__MINI_GLOBAL_FRONT_VERSION__;
            // todo: 临时
            if($__MINI_GLOBAL_FRONT_VERSION__ >= '1.2.2.24'){

            }else {
                $data = $data->where('is_wechat_sph', 0);
            }
        }
        if($__MINI_GLOBAL_MODE__ == 'examine'){
            $data = $data->where('post_type', '<>', 'video');
        }

        if($sort_by == 'id'){
            $data = $data->orderBy('id', 'desc');
        }else if($sort_by == 'hot'){
            $data = $data->orderBy('degree', 'desc')->orderBy('id', 'desc');
        }

        $data = $data->simplePaginate($limit);

        if($is_tenant){
            PostUtils::$force_show_multi_site = false;
        }
        $data = PostsRepositores::postsParame($data, $uid, $__MINI_GLOBAL_SCENE__);//文章详情

        return $this->success($data);
    }

    /**
     * 审核笔记
     * @param Request $request
     */
    public function auditPosts(Request $request)
    {
        $uid = $request->uid;
        $postsId = $request->id;
        $type = $request->type;
        $reject_msg = $request->reject_msg;
        if ($type == 0) {
            $result = WxPost::where('id', $postsId)->update(['is_examine' => 1]);
            if ($result) {
                $userId = WxPost::where('id', $postsId)->value('user_id');
                // 发送通知
                UserUtils::assistant_notice($userId, '您发表的笔记(id:<a href="/pages/sticky/sticky?id='.$postsId.'">'.$postsId.'</a>)已经审核通过');
            }
        } elseif ($type == 1) {
            $result = WxPost::where('id', $postsId)->update(['is_examine' => 2]);
            if ($result) {
                $userId = WxPost::where('id', $postsId)->value('user_id');
                // 发送通知
                UserUtils::assistant_notice($userId, '您发表的笔记(id:<a href="/pages/sticky/sticky?id='.$postsId.'">'.$postsId.'</a>)被驳回了，驳回原因：' . $reject_msg);
            }
        }


        return $this->success();


    }


    /**
     * 获取用户不喜欢的笔记
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function userBlack(Request $request){
        $uid = $request->uid;
        $post_set = get_user_meta($uid, 'feedback:notlike:post:set', 'j');
        if($post_set){
            $post_set = array_reverse($post_set);
            $data = WxPost::whereIn('id', $post_set)
                ->orderBy(DB::raw('FIND_IN_SET(id, "' . implode(",", $post_set) . '"' . ")"))->simplePaginate(10, FieldUtils::postInfoColums());

            PostUtils::reset_loop();
            $data->map(function ($v, $k) use ($uid){
                return PostUtils::WaterfallProcess($k, $v,80);
            });
            return $this->success($data);
        }else{
            return $this->fail(200003);
        }
    }


    public function promotion(Request $request){
        global $__MINI_GLOBAL_TENANT_ID__;
        $uid = $request->uid;
        $post_id = _empty_default_($request->post_id, 0);

        if(_empty_($post_id)){
            return $this->fail(200001);
        }

        $post_id = _abs((int)$post_id);

        if (request()->method() === 'GET') {
            // 处理GET请求
            $post = WxPost::find($post_id);
            $posts_content = _mini_phone(_mini_emoji(_mini_aite_replace($post->posts_content), true), true);
            if($posts_content){
                $s_content = preg_replace("/<(img|video).*?src[^\'\"]+[\'\"]([^\"\']+)[^>]+>/is", '', $posts_content);
                $s_content =trim_all_space(strip_tags(html_entity_decode($s_content)), true);
            }
            $post_title = PostUtils::get_the_title($s_content, $post->id);
            PostUtils::mediaProcess($post, $uid, 90004, 0, true);

            global $__MINI_GLOBAL_TENANT_ID__;
            $tmp_tenant_id = -1;
            if($__MINI_GLOBAL_TENANT_ID__ != $post->tenant_id){
                $tmp_tenant_id = $__MINI_GLOBAL_TENANT_ID__;
                $__MINI_GLOBAL_TENANT_ID__ = $post->tenant_id;
            }
            $post_options = Settings::get('app_promoted_post_options', ($__MINI_GLOBAL_TENANT_ID__ > 0 ? Settings::get('app_promoted_post_options', []) : []), true);
            if($tmp_tenant_id > 0){
                $__MINI_GLOBAL_TENANT_ID__ = $tmp_tenant_id;
            }

            return $this->success(
                [
                    'title' => $post_title,
                    'img' => $post->img,
                    'created_at' => $post->created_at->format('Y-m-d H:i:s'),
                    'author' => UserUtils::get_cached_user($post->user_id, false, false, $post->is_anonymous == 1),
                    'is_promoted' => $post->weight > time(),
                    'weight' => timetostr($post->weight),
                    'selectList' => $post_options,
                    'refreshCost' => Settings::get('app_promoted_post_refresh_cost', ($__MINI_GLOBAL_TENANT_ID__ > 0 ? Settings::get('app_promoted_post_refresh_cost', 1.0) : 1.0), true),
                    'rest_coin' => UserUtils::user_coins($uid)
                ]
            );

        } else{

        }
    }



    /**
     * 笔记反馈
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function feedback(Request $request){
        $uid = $request->uid;
        $post_id = $request->posts_id;

        // 1: 不喜欢该笔记 2：不喜欢该作者
        $type = $request->type;
        if(_empty_($post_id) || _empty_($type)){
            return $this->fail(200001);
        }

        if(!in_array($type, [1, 2])){
            return $this->fail(200004);
        }
        if($type == 1){
            $post_set = get_user_meta($uid, 'feedback:notlike:post:set', 'j');
            if(!in_array($post_id, $post_set)){
                $post_set[] = $post_id;
                update_user_meta($uid, 'feedback:notlike:post:set', array_unique($post_set), 'j');
                return $this->success([], 200, '标记为不喜欢，将不再展示该笔记');
            }else{
                // 要删除的特定值
                $post_set = array_filter($post_set, function ($value) use ($post_id) {
                    return $value != $post_id;
                });
                update_user_meta($uid, 'feedback:notlike:post:set', array_unique($post_set), 'j');
                return $this->success([], 200010, '已取消标记');
            }
        }else if($type == 2){
            $author_id = WxPost::where('id', $post_id)->value('user_id');
            if($author_id){
                $user_set = get_user_meta($uid, 'feedback:notlike:user:set', 'j');
                if(!in_array($author_id, $user_set)){
                    $user_set[] = $author_id;
                    update_user_meta($uid, 'feedback:notlike:user:set', array_unique($user_set), 'j');
                    return $this->success(['post_user_id'=>$author_id], 200, '标记为不喜欢，将不再展示该作者');
                }else{
                    // 要删除的特定值
                    $user_set = array_filter($user_set, function ($value) use ($author_id) {
                        return $value != $author_id;
                    });
                    update_user_meta($uid, 'feedback:notlike:user:set', array_unique($user_set), 'j');
                    return $this->success([], 200010, '已取消标记');
                }
            }else{
                return $this->fail(200003, [], '不存在该篇笔记');
            }
        }
        return $this->fail(200003, [], 'type参数错误');

    }

    /**
     * 笔记分享
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function share(Request $request){
        $uid = $request->uid;
        $posts_id_ = $request->posts_id;
        global $__MINI_GLOBAL_DEVICE__;
        if(is_string($posts_id_)){
            $posts_id_ = (int)$posts_id_;
        }
        $post_id = _abs($posts_id_);
        if(_empty_($post_id)){
            return $this->fail(200001);
        }
        global $__MINI_GLOBAL_PAYCODE_21__;

        $post = WxPost::find($post_id);
        $post_user_id = $post->user_id;
        $refer_id = $post->refer_id;
        $posts_content = $post->posts_content;
        if($posts_content){
            $s_content = preg_replace("/<(img|video).*?src[^\'\"]+[\'\"]([^\"\']+)[^>]+>/is", '', $posts_content);
            $s_content =trim_all_space(strip_tags(html_entity_decode($s_content)), true);
        }
        $post_title = $post->posts_title ?: PostUtils::get_the_title($s_content, $post->id);
        PostUtils::mediaProcess($post, $uid, 90003, 0, true);
        $post->img = Utils::imgWithStyle($post->img, 0, false, true).'?imageMogr2/thumbnail/200x200/crop/200x200/gravity/center/format/jpg/interlace/0/quality/100';
        $is_mini_admin = is_object_user_special($uid, $post->tenant_id);

        $result = [
            'user' => [],
            'url' => '',
            'social' => [

            ],
            'other' => [],
            // 临时加下
            'current_page' => 1
        ];

        if($uid && $uid > 0){
            if($__MINI_GLOBAL_PAYCODE_21__){
                if(!is_mini_examine_mode(11)){
                    $data = DB::table('wx_user')
                        ->whereIn('id', function ($query) use ($uid) {
                            $query->select('object_id')
                                ->from('wx_chat')
                                ->where('user_id', $uid)
                                ->groupBy('object_id')
                                ->orderByDesc('created_at');
                        })->simplePaginate(10, FieldUtils::userInfoColums());
                    if($data->isEmpty()){
                        $data = WxUser::where('is_official', 1)->simplePaginate(10, FieldUtils::userInfoColums());
                    }
                    $result['user'] = $data;
                }
            }

        }

        global $__MINI_GLOBAL_TENANT_ID__;
        if(Settings::get('app_h5_home', '')){
            $result['url'] = Settings::get('app_h5_home', '').'/#/pages/sticky/sticky?id='.$post_id . '&fph=1&from_user=' .$uid. '&tenant=' . $__MINI_GLOBAL_TENANT_ID__;
        }else{
            $result['url'] = env('APP_URL');
        }

        $the_only_path = '/pages/sticky/sticky?id=' . $post->id. '&fph=1&from_user=' .$uid. '&tenant=' . $__MINI_GLOBAL_TENANT_ID__;

        $share_types = Settings::get('app_post_social_share_types', []);
        foreach (['refer', 'wechat', 'timeline', 'qq', 'qzone', 'weibo'] as $key){
            if(!in_array($key, $share_types)){
                continue;
            }
            if($key == 'refer'){
                if($refer_id > 0){
                    continue;
                }else{
                    if($__MINI_GLOBAL_PAYCODE_21__){
                        $result['social'][] = [
                            'action' => 'refer',
                            'color' => Settings::get('--color-primary', '#FC3A72'),
                            'text' => '站内转发',
                            'icon' => 'mini-icon mini-zhanneizhuanfa',
                            'unicode' => 'e699'
                        ];
                    }
                }
            }else if($key == 'wechat'){
                $result['social'][] = [
                    'action' => 'wechat',
                    'color' => '#57be6a',
                    'text' => '微信好友',
                    'icon' => 'mini-icon mini-weixin',
                    'unicode' => 'e60b',
                    'share' => json_encode([
                        'provider' => 'weixin',
                        'type' => _empty_(Settings::get('app_meta_appid',  '')) ? 0 : 5,
                        'title' => $post_title,
                        'scene' => 'WXSceneSession',
                        'href' => $result['url'],
                        'imageUrl' => $post->img,
                        'miniProgram' => [
                            'id' => Settings::get('app_meta_appid',  ''),
                            'path' => $the_only_path,
                            'type' => 0,
                            'webUrl' => $result['url']
                        ]
                    ]),

                ];
            }else if($key == 'timeline'){
                if($__MINI_GLOBAL_DEVICE__ != 'mp'){
                    $result['social'][] = [
                        'action' => 'timeline',
                        'color' => '#80cc46',
                        'text' => '朋友圈',
                        'icon' => 'mini-icon mini-pengyouquan1',
                        'unicode' => 'e669',
                        'share' => json_encode([
                            'provider' => 'weixin',
                            'type' => 0,
                            'title' => $post_title,
                            'summary' => $s_content,
                            'scene' => 'WXSceneTimeline',
                            'href' => $result['url'],
                            'imageUrl' => $post->img,
                            'miniProgram' => [
                                'id' => Settings::get('app_meta_appid',  ''),
                                'path' => $the_only_path,
                                'type' => 0,
                                'webUrl' => $result['url']
                            ]
                        ])
                    ];
                }
            }else if($key == 'qq'){
                if(!_empty_(Settings::get('app_qq_app_appid', ''))){
                    if($__MINI_GLOBAL_DEVICE__ != 'mp') {
                        $result['social'][] = [
                            'action' => 'qq',
                            'color' => '#54b4ef',
                            'text' => 'QQ好友',
                            'icon' => 'mini-icon mini-qq1',
                            'unicode' => 'e66c',
                            'share' => json_encode([
                                'provider' => 'qq',
                                'type' => 1,
                                'title' => $post_title,
                                'summary' => $s_content,
                                'href' => $result['url'],
                                'imageUrl' => $post->img
                            ])

                        ];
                    }
                }
            }else if($key == 'qzone'){
                if(!_empty_(Settings::get('app_qq_app_appid', ''))){
                if($__MINI_GLOBAL_DEVICE__ != 'mp') {
                    $result['social'][] = [
                        'action' => 'qzone',
                        'color' => '#f7cf46',
                        'text' => 'QQ空间',
                        'icon' => 'mini-icon mini-Rrl_s_112',
                        'unicode' => 'e62a',
                        'share' => json_encode([
                                'provider' => 'qq',
                                'type' => 1,
                                'title' => $post_title,
                                'href' => $result['url'],
                                'imageUrl' => $post->img
                            ])
                        ];
                    }
                }
            }else if($key == 'weibo'){
                if(!_empty_(Settings::get('app_weibo_app_appid', ''))){
                    if($__MINI_GLOBAL_DEVICE__ != 'mp') {
                        $result['social'][] = [
                            'action' => 'weibo',
                            'color' => '#d4382a',
                            'text' => '微博',
                            'icon' => 'mini-icon mini-weibo',
                            'unicode' => 'e73c',
                            'share' => json_encode([
                                'provider' => 'sinaweibo',
                                'type' => 0,
                                'title' => $post_title,
                                'href' => $result['url'],
                                'imageUrl' => $post->img
                            ])

                        ];
                    }
                }
            }
        }

        $system_types = Settings::get('app_post_social_system_types', ['showCode', 'copyUrl', 'feedback-notlike-1', 'video-url','promotion', 'report' ]);
        // promotion
        foreach (['showCode', 'edit', 'copyUrl', 'feedback-notlike-1', 'video-url', 'promotion', 'report', 'poster2'] as $key){
            if(!in_array($key, $system_types)){
                continue;
            }
            if($key == 'showCode'){
                $result['other'][] = [
                    'text' => '生成海报',
                    'icon' => 'mini-icon mini-shengchenghaibao',
                    'action' => 'showCode',
                    'unicode' => 'e697',
                ];
            }else if($key == 'poster2'){
                $result['other'][] = [
                    'text' => '小海报',
                    'icon' => 'mini-icon mini-shengchenghaibao',
                    'unicode' => 'e697',
                    'action' => 'poster2'
                ];
            }else if($key == 'edit'){
                if($refer_id > 0 || $post->vote_id > 0){

                }else{
                    if(($post_user_id == $uid && $post->posts_state === 0) || $is_mini_admin) {
                        $result['other'][] = [
                            'text' => '编辑',
                            'icon' => 'mini-icon mini-xie',
                            'unicode' => 'e6fd',
                            'action' => 'slider',
                            'target_type' => 6,
                            'target_id' => '/pages/creat/index/creat?edit=' . $post_id
                        ];
                    }
                }
            }else if($key == 'video-url'){
                if($post->post_type == 'video'){
                    $result['other'][] = [
                        'text' => '视频下载',
                        'icon' => 'mini-icon mini-xiazai2',
                        'action' => 'video-url',
                        'unicode' => 'e63c',
                        'video_url' => $post->video['video_url']
                    ];
                }
            }else if($key == 'copyUrl'){
                $result['other'][] = [
                    'text' => '复制链接',
                    'icon' => 'mini-icon mini-fuzhilianjie',
                    'unicode' => 'e691',
                    'action' => 'copyUrl'
                ];
            }else if($key == 'feedback-notlike-1'){
                $result['other'][] = [
                    'text' => '不喜欢',
                    'icon' => 'mini-icon mini-buxihuan',
                    'unicode' => 'e69d',
                    'action' => 'feedback-notlike-1',
                    'posts_id' => $post_id
                ];
            }else if($key == 'report'){
                if($post_user_id != $uid){
                    $result['other'][] = [
                        'text' => '举报',
                        'icon' => 'mini-icon mini-jubao',
                        'unicode' => 'e694',
                        'action' => 'report'
                    ];
                }
            }else if($key == 'promotion'){
                global $__MINI_GLOBAL_PAYCODE_5__;
                if($__MINI_GLOBAL_PAYCODE_5__){
                    $result['other'][] = [
                        'text' => '笔记推广',
                        'icon' => 'mini-icon mini-fufeituiguang1',
                        'unicode' => 'e6f3',
                        'action' => 'promotion'
                    ];
                }
            }
        }

        if($post_user_id == $uid || $is_mini_admin){
            $result['other'][] = [
                'text' => '删除',
                'icon' => 'mini-icon mini-shanchu211',
                'unicode' => 'e6f3',
                'action' => 'delete',
                'posts_id' => $post->id
            ];
        }

//        _logger_(__file__, __line__, $result);
        return $this->success($result);

    }



    /**
     * 获取文章分享二维码
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function makeShowQcode(Request $request)
    {
        $postsId = _abs($request->posts_id);
        $uid = $request->uid;
        global $__MINI_GLOBAL_DEVICE__;
        if(_empty_($postsId)){
            return $this->fail(200001);
        }
        $data = [];
        $data['title'] = Settings::get('about_title', '');

        $post = WxPost::find($postsId);
        if(_empty_($post)){
            return $this->fail(200003);
        }
        $post_user_id = $post->user_id;
        $refer_id = $post->refer_id;
        $posts_content = _mini_phone(_mini_emoji(_mini_aite_replace($post->posts_content), true), true);
        if($posts_content){
            $s_content = preg_replace("/<(img|video).*?src[^\'\"]+[\'\"]([^\"\']+)[^>]+>/is", '', $posts_content);
            $s_content =trim_all_space(strip_tags(html_entity_decode($s_content)), true);
        }
        $post_title = PostUtils::get_the_title($s_content, $post->id, 50);
        PostUtils::mediaProcess($post, $uid, 90004, 0, true);

        // ['glass'=>'', 'theme'=>'black/white', 'attach_id'=>id]
        $poster_glass = get_post_meta($post->id, 'post_poster_glass_obj', 'j');
        if(_empty_($poster_glass)){
            $attach_id = FileUtils::get_url_attach_id($post->img);
            if($attach_id){
                $post_poster_glass_obj = [
                    'glass' => '',
                    'theme' => '',
                    'attach_id' => $attach_id
                ];
                $first_glasses = $post->img . '?imageMogr2/thumbnail/630x800/crop/630x800/gravity/center/format/png/interlace/0/blur/50x1';
                $path = ImageUtils::upload_url_img($first_glasses);
                if($path && $path['url']){
                    // 二次上传
                    $path2 = ImageUtils::upload_url_img($path['url']. '?imageMogr2/thumbnail/630x800/crop/630x800/gravity/center/format/png/interlace/0/blur/50x1');
                    if($path2 && $path2['url']){
                        // 三次上传
                        $path3 = ImageUtils::upload_url_img($path2['url']. '?imageMogr2/thumbnail/630x800/crop/630x800/gravity/center/format/png/interlace/0/blur/50x1');
                        if($path3 && $path3['url']){

                            // 四次上传
                            $path4 = ImageUtils::upload_url_img($path3['url']. '?imageMogr2/thumbnail/630x800/crop/630x800/gravity/center/format/png/interlace/0/blur/50x1');
                            if($path4 && $path4['url']){
                                $post_poster_glass_obj['glass'] = $path4['url'];
                                update_post_meta($post->id, 'post_poster_glass_obj', $post_poster_glass_obj, 'j');
                                FileUtils::force_del_url_file($path3['url']);
                                $data['glass'] = $path4['url'] . '?imageMogr2/thumbnail/630x800/crop/630x800/gravity/center/format/png/interlace/0/blur/50x1';
                            }else{
                                $post_poster_glass_obj['glass'] = $path3['url'];
                                update_post_meta($post->id, 'post_poster_glass_obj', $post_poster_glass_obj, 'j');
                                $data['glass'] = $path3['url'] . '?imageMogr2/thumbnail/630x800/crop/630x800/gravity/center/format/png/interlace/0/blur/50x1';
                            }

                        }else{
                            $post_poster_glass_obj['glass'] = $path2['url'];
                            update_post_meta($post->id, 'post_poster_glass_obj', $post_poster_glass_obj, 'j');
                            $data['glass'] = $path2['url'] . '?imageMogr2/thumbnail/630x800/crop/630x800/gravity/center/format/png/interlace/0/blur/50x1';
                        }

                    }else{
                        $post_poster_glass_obj['glass'] = $path['url'];
                        update_post_meta($post->id, 'post_poster_glass_obj', $post_poster_glass_obj, 'j');
                        $data['glass'] = $path['url'] . '?imageMogr2/thumbnail/630x800/crop/630x800/gravity/center/format/png/interlace/0/blur/50x1';
                    }
                }else{
                    $data['glass'] = $post->img . '?imageMogr2/thumbnail/630x800/crop/630x800/gravity/center/format/png/interlace/0/blur/50x1';
                }
                UpdatePosterGlassJob::dispatch($post->id);
            }
        }else{
            if(FileUtils::get_url_attach_id($post->img) == $poster_glass['attach_id']){
                _logger_(__file__, __line__, $poster_glass['theme']);
                if(_empty_($poster_glass['theme'])){
                    UpdatePosterGlassJob::dispatch($post->id);
                }
                $data['glass'] = $poster_glass['glass'] . '?imageMogr2/thumbnail/630x800/crop/630x800/gravity/center/format/png/interlace/0/blur/50x1';
            }else{
                update_post_meta($post->id, 'post_poster_glass_obj', null, 'j');
                FileUtils::force_del_url_file($poster_glass['glass']);
            }
        }


        $user = WxUser::where('id', $post_user_id)->first(FieldUtils::userInfoColums());
        if($user){

        }else{
            $user = ['user_name'=>'未知用户'];
        }
        if($post->is_anonymous == 1){
            $anonymous_info = UserUtils::get_anonymous_info($user);
            if($anonymous_info){
                $user['user_name'] = $anonymous_info['anonymous_name'];
                $user['user_avatar'] = $anonymous_info['anonymous_avatar'];
            }else{
                $user['user_name'] = '匿名';
            }
        }
        $data['user'] = $user;

        if(empty($post->img)){
            return $this->fail(200006, [], '请先配置“笔记海报默认图片”');
        }

        $page = 'pages/sticky/sticky';
        $code_url = Utils::getMiniCode($page, 'id='.$postsId, $uid);
        $data['qrcode'] = $code_url;
        $data['img'] = $post->img.'?imageMogr2/quality/100/interlace/0/crop/630x800/gravity/center/thumbnail/x800';
        $data['content'] = $post_title;
        $data['tip'] =  Settings::get('app_post_poster_bottom_tip', '❤ 扫一扫，找到你想要的生活');

        if($poster_glass){
            $data['tip_color'] = _array_key($poster_glass, 'theme', 'black') == 'white' ? '#333' : '#FFF';
        }else{
            $data['tip_color'] = '#FFF';
        }

        if(Settings::get('is_multi_site', 0) > 0){
            $circle_tip = WxTenant::where('tenant_id', $post->tenant_id)->value('name');
        }else{
            if($post->circle_id > 0){
                $circle_tip = WxCircle::where('id', $post->circle_id)->value('circle_name');
            }else{
                $circle_tip = '广场';
            }
        }

        $data['poster2'] = [
            'content' => $post_title,
            'contentImg' => ($post->img == Settings::get('img_post_poster_default', '')) ? '' : ($post->img. '?imageMogr2/quality/100/interlace/0/crop/630x800/gravity/center/thumbnail/x800'),
            'avatar' => $user->user_avatar,
            'locationText' => $circle_tip,
            'locationImg' => env('APP_URL') . '/statics/images/playbill/post/ring.png',
            'userName' => $user->user_name,
            'code' => $code_url,
            'textImg' => env('APP_URL') . '/statics/images/playbill/post/poster-text.png'
        ];
        if(Settings::get('app_h5_home', '')){
            $data['url'] = Settings::get('app_h5_home', '').'/#/pages/sticky/sticky?id='.$post->id;
        }else{
            $data['url'] = env('APP_URL');
        }

        $social = [];
        $share_types = Settings::get('app_post_poster_share_types', []);
        foreach (['wechat', 'timeline', 'qq', 'qzone', 'weibo', 'save'] as $key){
            if(!in_array($key, $share_types)){
                continue;
            }
            if($key == 'wechat'){
                $social[] = [
                    'action' => 'wechat',
                    'color' => '#57be6a',
                    'text' => '微信好友',
                    'icon' => 'mini-icon mini-weixin',
                    'share' => json_encode([
                        'provider' => 'weixin',
                        'type' => 2,
                        'title' => $data['content'],
                        'scene' => 'WXSceneSession',
                        'href' => $data['url'],
                        'imageUrl' => $data['img'],
                        'miniProgram' => [
                            'id' => Settings::get('app_meta_appid',  ''),
                            'path' => '/pages/sticky/sticky?id=' . $post->id,
                            'type' => 0,
                            'webUrl' => $data['url']
                        ]
                    ]),

                ];
            }else if($key == 'timeline'){
                if($__MINI_GLOBAL_DEVICE__ != 'mp'){
                    $social[] = [
                        'action' => 'timeline',
                        'color' => '#80cc46',
                        'text' => '朋友圈',
                        'icon' => 'mini-icon mini-pengyouquan1',
                        'share' => json_encode([
                            'provider' => 'weixin',
                            'type' => 2,
                            'title' => $data['content'],
                            'scene' => 'WXSceneTimeline',
                            'href' => $data['url'],
                            'imageUrl' => $data['img']
                        ])
                    ];
                }

            }else if($key == 'qq'){
                if($__MINI_GLOBAL_DEVICE__ != 'mp') {
                    $social[] = [
                        'action' => 'qq',
                        'color' => '#54b4ef',
                        'text' => 'QQ好友',
                        'icon' => 'mini-icon mini-qq1',
                        'share' => json_encode([
                            'provider' => 'qq',
                            'type' => 2,
                            'title' => $data['content'],
                            'summary' => $data['content'],
                            'href' => $data['url'],
                            'imageUrl' => $data['img']
                        ])

                    ];
                }
            }else if($key == 'qzone'){
                if($__MINI_GLOBAL_DEVICE__ != 'mp') {
                    $social[] = [
                        'action' => 'qzone',
                        'color' => '#f7cf46',
                        'text' => 'QQ空间',
                        'icon' => 'mini-icon mini-Rrl_s_112',
                        'share' => json_encode([
                            'provider' => 'qq',
                            'type' => 1,
                            'title' => $data['content'],
                            'href' => $data['url'],
                            'imageUrl' => $data['img']
                        ])

                    ];
                }
            }else if($key == 'weibo'){
                if($__MINI_GLOBAL_DEVICE__ != 'mp') {
                    $social[] = [
                        'action' => 'weibo',
                        'color' => '#d4382a',
                        'text' => '微博',
                        'icon' => 'mini-icon mini-weibo',
                        'share' => json_encode([
                            'provider' => 'sinaweibo',
                            'type' => 0,
                            'title' => $data['content'],
                            'href' => $data['url'],
                            'imageUrl' => $data['img']
                        ])

                    ];
                }
            }else if($key == 'save'){
                $social[] = [
                    'action' => 'save',
                    'color' => '#999999',
                    'text' => '保存到相册',
                    'icon' => 'mini-icon mini-xiazai2',
                ];
            }
        }
        $data['social'] = $social;
        if($code_url){
            return $this->success($data);
        }else{
            return $this->fail(300001, $data);
        }
    }


    /**
     * 审核笔记
     * @param Request $request
     */
    public function getExceptionalList(Request $request)
    {

        $postsId = $request->posts_id;
        if(_empty_($postsId)){
            return $this->fail(200001);
        }
        $postsId = _abs($postsId);
        $data = WxExceptional::where('posts_id', $postsId)
            ->orderBy('id', 'desc')
            ->get();

        $data->map(function ($v) {
            $v->exceptional_date = format_datetime($v->created_at);
            $v->user = WxUser::where('id', $v->user_id)->first(FieldUtils::userInfoColums());
        });

        return $this->success($data);

    }

    /** 视频推荐接口
     * @param Request $request
     */
    public function recommendedVideos(Request $request){
        $page = $request->page ?: 0;
        $offset = $page * 10;
        $post_id= $request->id;
        if(_empty_($post_id)){
            return $this->fail(200001);
        }
        $uid = $request->uid;
        $data_res = [];
        $post_videos = WxPost::Join('wx_posts_video', 'wx_posts.id', '=', 'wx_posts_video.posts_id')->where('wx_posts.posts_state', 0)->orwhere('wx_posts.id', $post_id)->inRandomOrder()
            ->skip($offset)->take(10)->get(['wx_posts_video.posts_id', 'wx_posts_video.id', 'wx_posts.posts_content', 'wx_posts.user_id', 'wx_posts_video.video_url', 'wx_posts_video.video_thumb_url', 'wx_posts.created_at']);
        $post_videos->map(function ($v) use ($uid, &$data_res, $post_id){
            global $__MINI_GLOBAL_CURRENT_USER_ID__;
            $v->user = WxUser::where('id', $v->user_id)
                ->first(FieldUtils::userInfoColums());//发帖人

            $v->like_count = PostsRepositores::likeCont($v->id); // 笔记喜欢数量
            $v->is_my_posts = $__MINI_GLOBAL_CURRENT_USER_ID__ == $v->user_id; // 是否是我的笔记
            $v->is_follow_user = WxPost::isFollowUser($uid, $v->user_id);// 是否关注该用户
            $v->is_like = WxPost::isLike($uid, $v->id); // 是否喜欢
            $v->is_collect = WxPost::isCollec($uid, $v->id); // 是否收藏
            $v->comment = (new WxPost())
                ->getComment($v->id, ['user_name', 'comment_content', 'user_id', 'posts_user_id', 'comment_img_url']); // 评论
            $v->comment_count = WxCommentRepositores::commentCount($v->id);//评论数量
            $item = [
                'src' => $v->video_url,
                'content' => $v->posts_content,
                'flag' => true,
                'check' => $v->is_like,
                'like' => $v->like_count,
                'isFollow' => $v->is_follow_user,
                'comment' => $v->comment_count,
                'avater'=> $v->user->user_avatar,
                'initialTime' => 0,
                'at' => $v->user->user_name,
                'duration' => 999,
                'uid' => $v->user->id,
                'pid' => $v->posts_id,
                'vid' => $v->id,
                'isAuthor' =>  $v->is_my_posts,
                'date' => $v->created_at->format('Y-m-d H:i:s')
            ];
            if($v->posts_id == $post_id){
                array_unshift($data_res, $item);
            }else{
                $data_res[] = $item;
            }

        });

        if($data_res){
            return $this->success($data_res);
        }else{
            return $this->fail(200003);
        }

    }

}
